这是我参与2022首次更文挑战的第17天,活动详情查看:2022首次更文挑战
问题:
给定一个整数数组 nums 和一个整数目标值 target,在该数组中找出和为目标值 target的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现(假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现)
举例:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] (题目来自力扣)
分析:
第一种:
我在看了题目后,最直接的想法是全部遍历一遍(这是最简单也最容易想到的) 例如结合结合上面的例子,nums[0]和nums[1],nums[2],nums[3]相加是否等于目标值,再依次遍历,这样的做法是最简单,最暴力的解法
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexs = new int[2]; //根据题目说只会对应一种答案 所以在这里初始化2
if(nums == null || nums.length == 0){
return indexs;
}
for(int i = 0; i < nums.length; i++){ //双层循环
for(int j = i+1; j <= nums.length; j ++){
if(nums[i]+nums[j] == target){
indexs[0] = i;
indexs[1] = j;
return indexs;
}
}
}
return indexs;
}
}
在线运行的结果:
但这个运行的时间复杂度时o(n^2)
第二种:
结合hash表,如果不经常接触算法,这个不容易想往上面取想。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexs = new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];//减去一个数的差值是否存在 存在即可更新indexs
if(map.containsKey(temp)){
indexs[1] = i;
indexs[0] = map.get(temp);
}
map.put(nums[i], i);
}
return indexs;
}
}
第二种方法和第一种方法有了一些改进 而不是取循环遍历所有的数,而是引入了hash表,hash查找速度较快,在java中,我们知道hash表的数据结构是数组加链表(java8后面是红黑树),所以相比于两次循环和hash查找而言,hash查找速度更快,时间复杂度也降低了 其中我们在map中存放数据时,是先判断再存数据,这样就可以减少内存的开销。