This problem is similar to Two Sum.
To solve this problem, we can use two pointers to scan the array from both sides. See Java solution below:
public int[] twoSum(int[] numbers, int target) { if (numbers == null || numbers.length == 0) return null; int i = 0; int j = numbers.length - 1; while (i < j) { int x = numbers[i] + numbers[j]; if (x < target) { ++i; } else if (x > target) { j--; } else { return new int[] { i + 1, j + 1 }; } } return null; } |
This will not return correct answer, for example [2, 3, 4, 6, 7, 8] and target is 9
what will achieve this is [1,5] but the correct answer is [2,4] because it will sum up to 9 before [1,5]
actually in the problem 1, it mentioned that “Please note that your returned
answers (both index1 and index2) are not zero-based.”, this is the two sun follow up problem, so I think that why they +1 here.
How binary search works for 2 sum?
Yes. It should be return new int[]{i,j};
Shouldn’t it return
return new int[] { i, j };
This code is O(n). It can be O(log(n)). The code in Python: https://github.com/renzon/code_interview_training/blob/master/two_sum.py