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.
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. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
已经排好序了,当然会想到二分搜索,不过我想到的比较蠢。。。
1 class Solution { 2 public: 3 vector twoSum(vector & numbers, int target) { 4 5 int n = numbers.size(); 6 vector res; 7 8 for (int i = 0; i < n; ++i) 9 {10 int solu = target - numbers[i];11 int lo = 0, hi = n - 1;12 while (lo <= hi)13 {14 int mid = lo + (hi - lo) / 2;15 16 if (solu < numbers[mid])17 {18 hi = mid - 1;19 }20 else if (solu > numbers[mid])21 {22 lo = mid + 1;23 }24 else25 {26 res.push_back(i + 1);27 if(numbers[i]==numbers[mid])28 {29 res.push_back(i + 2);30 return res;31 }32 res.push_back(mid + 1);33 return res;34 }35 }36 }37 }38 };
贴上一个两端逼近的吧,更加简洁清晰:
1 vector twoSum(vector & numbers, int target) { 2 3 int l = 0; 4 int r = numbers.size() -1; 5 while(l < r){ 6 if(numbers[l] + numbers[r] == target){ 7 vector res{l+1,r+1}; 8 return res; 9 }10 else if(numbers[l] + numbers[r] > target){11 r--;12 }13 else{14 l++;15 }16 }17 }