双指针提升有序数组查找效率

题目链接-来源:力扣(LeetCode)

输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]

思路:

使用两个指针,一个从数组头部向后遍历,一个从数组尾部向前遍历。二者指向的元素之和,可以与 target 作比较。由于数组本身有序,当和较大时,尾指针左移可使和变小,反之头指针右移可使和变大。就这样慢慢逼近 target。

时间复杂度:O(n)
空间复杂度:O(1)

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] twoSum(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
return new int[] {nums[left], nums[right]};
}
}
return null;
}
}