Two Sum II - Input array is sorted
Input array is sorted
- Time: O(N)
- Space: O(1)
public int[] twoSum2(int[] nums, int target) {
if (nums == null || nums.length == 0) return null;
int i = 0;
int j = nums.length - 1;
while (i < j) {
int x = nums[i] + nums[j];
if (x < target) {
i++;
} else if (x > target) {
j--;
} else {
return new int[]{i + 1, j + 1};
}
}
return new int[]{};
}