167. Two Sum II - Input array is sorted

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     vector<int> twoSum(vector<int>& numbers, int target) 
12     {
13         int sz=numbers.size();
14         int i=0,j=sz-1;
15         while(numbers[i]+numbers[j]>target)
16             --j;
17         while(i<j)
18         {
19             if(numbers[i]+numbers[j]<target)
20                 ++i;
21             else if(numbers[i]+numbers[j]>target)
22                 --j;
23             else
24                 return vector<int>{i+1,j+1};
25         }
26     }
27 };

在有序数组中找两个数的的序号,使其和为目标值。

两头往中间靠,必然能找到那俩数。

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9067654.html