输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[2,7] 或者 [7,2] 示例 2:
输入:nums = [10,26,30,31,47,60], target = 40 输出:[10,30] 或者 [30,10]
限制:
1 <= nums.length <= 10^5 1 <= nums[i] <= 10^6
解题思路
复杂度分析:
时间复杂度 O(N) : N 为数组 nums 的长度;双指针共同线性遍历整个数组。
空间复杂度 O(1) : 变量 i, j 使用常数大小的额外空间。
代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
int i = 0, j = nums.length - 1;
while (i < j) {
int s = nums[i] + nums[j];
if (s == target) {
return new int[]{nums[i], nums[j]};
} else if (s > target) {
j--;
} else {
i++;
}
}
return new int[0];
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
HashSet<Integer> hashSet = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
int a = nums[i];
int b = target - a;
if (hashSet.contains(b)) {
result[0] = a;
result[1] = b;
break;
} else {
hashSet.add(a);
}
}
return result;
}
}