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

two pointers. 没什么好说的.

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