Return indices of the two numbers added up to the target.
Question
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. See it on Leetcode
1
2
3
For example:
Input numbers = [2, 7, 11, 15], with target = 9
It should return [1, 2]
Hint
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Your returned answers (both index1 and index2) are not zero-based.
Each input would have exactly one solution.
Solution in Java, C++ and Javascript
java
cpp
js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclassSolution{ publicint[] twoSum(int[] numbers, int target) { int left = 0, right = numbers.length - 1; while (left < right) { if (numbers[left] + numbers[right] == target) { returnnewint[]{left + 1, right + 1}; } elseif (numbers[left] + numbers[right] < target) { left++; } else { right--; } } thrownew IllegalArgumentException("No two sum solution"); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> ans; int left = 0, right = numbers.size() - 1; while (left < right) { if (numbers[left] + numbers[right] == target) { ans.push_back(left + 1); ans.push_back(right + 1); return ans; } elseif (numbers[left] + numbers[right] > target) { right--; } else { left++; } } return ans; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * @param {number[]} numbers * @param {number} target * @return {number[]} */ var twoSum = function(numbers, target) { var left = 0, right = numbers.length - 1; while (left < right) { if (numbers[left] + numbers[right] == target) { returnnewArray(left + 1, right + 1); } elseif (numbers[left] + numbers[right] < target) { left++; } else { right--; } } returnnewArray(0, 0); };
Solution in Golang
go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
functwoSum(numbers []int, target int) []int { left := 0 right := len(numbers) - 1 for left < right { switch { case numbers[left] + numbers[right] > target: right-- case numbers[left] + numbers[right] < target: left++ default: return []int{left + 1, right + 1} } } return []int{0, 0} }