608. 两数和-输入已排序的数组

给定一个已经按升序排列的数组,找到两个数使他们加起来的和等于特定数。
函数应该返回这两个数的下标,index1必须小于index2。注意返回的值不是 0-based。

 注意事项

你可以假设每个输入刚好只有一个答案

 
样例

给定数组为 [2,7,11,15] ,target = 9
返回 [1,2]

 
如果这个数组是乱序,可以考虑套两层循环暴力解
但是关键点就在于这个数组是升序,那么就可以从两头往内缩着搜索
 
 1 vector<int> twoSum(vector<int> &nums, int target) {
 2         // write your code here
 3         vector<int> result;
 4         int low=0;
 5         int high=nums.size()-1;
 6         while(low<high){
 7             if(nums[low]+nums[high]>target){
 8                 high--;
 9             }
10             else if(nums[low]+nums[high]<target){
11                 low++;
12             }
13             else{
14                 result.push_back(low+1);
15                 result.push_back(high+1);
16                 return result;
17             }
18         }
19     }

 

posted @ 2017-12-19 04:03  三人木君  阅读(152)  评论(0编辑  收藏  举报