首页 > 其他分享 >LeetCode 167. Two Sum II - Input array is sorted(双指针)

LeetCode 167. Two Sum II - Input array is sorted(双指针)

时间:2022-10-18 14:07:10浏览次数:101  
标签:right int Sum Two II vector numbers ans left

​题目​

题意:找出数组里两个数字之和为指定数字的两个下标。

题解:双指针

class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {

int left = 0;
int right = numbers.size()-1;
vector<int> ans;
while(left < right)
{
if(numbers[left]+numbers[right]>target)
{
right--;
}
else if(numbers[left]+numbers[right]<target)
{
left++;
}
else
{
ans.push_back(left+1);
ans.push_back(right+1);
break;
}

}

return ans;

}
};



标签:right,int,Sum,Two,II,vector,numbers,ans,left
From: https://blog.51cto.com/u_15834522/5766259

相关文章