LeetCode 167.
Tags: LeetCode
Question
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order,
find two numbers such that they add up to a specific target number.
Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Intuition
First thought: Iterate the array and use BS to find another possible value.
Second thought: Use two pointers to optimize time complexity from O(nlogn) to O(n)
Complexity
-
Time complexity: O(nlogn)
-
Space complexity: O(1)
Code 1
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length-1;
int tar = 0, mid = 0;
for (int i=0; i<numbers.length; i++) {
tar = target - numbers[i];
while (left <= right) {
mid = left + (right - left) / 2;
if (i != mid && numbers[mid] == tar) {
return new int[]{i + 1, mid + 1};
}
if (numbers[mid] > tar) {
right = mid - 1;
}else{
left = mid + 1;
}
}
left = 0;
right = numbers.length - 1;
}
return new int[]{-1, -1};
}
}
Complexity
-
Time complexity: O(n)
-
Space complexity: O(1)
Code 2
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int total = numbers[left] + numbers[right];
if (total == target) {
return new int[]{left + 1, right + 1};
} else if (total > target) {
right--;
} else {
left++;
}
}
return new int[]{-1, -1};
}
}
Check out the description of this problem at LC 167.