[LeetCode]两数之和 II - 输入有序数组
题目
代码
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int start=0,end=numbers.size()-1;
vector<int> result;
while(start<end)
{
if(numbers[start]+numbers[end]>target)
end--;
else if(numbers[start]+numbers[end]<target)
start++;
else
break;
}
result.push_back(start+1);
result.push_back(end+1);
return result;
}
};
思路
利用双指针的思想,从数组头和尾之和开始比较,如果start和end的值大于target,则移动end,如果小于target,则移动start,最后能得到start和end和等于target的情况,则start和end为所求的数值索引
https://github.com/li-zheng-hao