首页 > 代码库 > leetcode-Two Sum II - Input array is sorted-167

leetcode-Two Sum II - Input array is sorted-167

输入一个递增序列,求两个元素的和等于target的下标

数组求和系列问题,用头尾指针法,ON

 1 class Solution { 2 public: 3     vector<int> twoSum(vector<int>& numbers, int target) { 4         vector<int> v; 5         int i=0,j=numbers.size()-1; 6         while(i<j){ 7             int sum=numbers[i]+numbers[j]; 8             if(sum==target){ 9                 v.push_back(i+1);10                 v.push_back(j+1);11                 return v;12             }13             if(sum>target) j--;14             else i++;15         }16         return v;17     }18 };

 

leetcode-Two Sum II - Input array is sorted-167