
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

1.常规思路两遍遍历数组,使用if条件判断。
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
- 双重for循环嵌套,时间复杂度位O(n²)空间复杂度O(1)
2.使用hash表,以空间换取时间,代码如下
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0;i < nums.length;i++){
map.put(nums[i],i);
}
for(int i = 0;i < nums.length;i++){
int sum = target - nums[i];
if(map.containsKey(sum) && map.get(sum) != i){
return new int[] {map.get(sum),i};
}
}
throw new RuntimeException("error");
}
- hash表的查找时间为O(1),占用空间为O(n),所以时间复杂度变为O(n),空间复杂度O(n)
- 可以只是用一个for循环完成,写成两个便于理解
当给定集合中出现重复数字,在map中后边把前边的覆盖掉,for循环遍历时先遇到前边被覆盖的那一个,结果不受影响。