1: class Solution {
2: public:
3: vector<int> twoSum(vector<int>& numbers, int target) {
4: int l = 0, r = numbers.size()-1;
5: while (l < r) {
6: int sum = numbers[l] + numbers[r];
7: if (sum == target) break;
8: else if (sum < target) l++;
9: else r--;
10: }
11: return vector<int>{l+1, r+1};
12: }
13: };
Monday, August 8, 2016
167. Two Sum II - Input array is sorted
Not much to say. An easy two pointers solution with O(N) running time. Of course, it can be solved by binary search but it may cost NlogN running time.
Labels:
amazon,
array,
leetcode,
two pointers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment