LC.P167[两数之和II-输入有序数组]

方法一:双指针

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0, r = numbers.length - 1;
while (l < r) {
int sum = numbers[l] + numbers[r];
if (sum < target) ++l;
else if (sum > target) --r;
else return new int[]{l + 1, r + 1};
}
return new int[]{};
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$