两数之和

这是LeetCode热题100的第1题 1.两数之和

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

1
2
3
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

1
2
输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

1
2
输入:nums = [3,3], target = 6
输出:[0,1]

提示:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • 只会存在一个有效答案

进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?

解法一:

可以分别枚举第一个数和第二个数,然后检查它们的和,如果满足题意,则返回

为了避免同一个数,我们可以从当前数的下一个开始枚举第二个数

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int[] twoSum(int[] a, int target) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] + a[j] == target) return new int[]{i, j};
}
}
return null;
}
}

解法二:

为了满足进阶的要求,我们可以通过哈希表来优化第二个数的寻找过程,如果我们能提前记录好之前的数,那么到当前位置,我们只需要看之前有没有存在过目标值和当前值的差,如果有,即可返回答案

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] a, int target) {
Map<Integer, Integer> pos = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if (pos.containsKey(target - a[i])) {
return new int[]{pos.get(target - a[i]), i};
}
pos.put(a[i], i);
}

return null;
}
}