您的位置:首页 > 编程语言 > C语言/C++

LeetCode- 167. Two Sum II - Input array is sorted - 思路详解- C++

2017-01-11 15:32 453 查看

题目

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

翻译

给定一个已经升序排列的数组,找到两个数,这两个数之和等于目标值。

twoSum函数,应该返回这两个数的下标索引。且index1必须小于index2.注意:下标从1开始计数

思路

思路1

首先是暴利法,即两次循环嵌套。时间复杂度O(n^n);

对于大样例会导致超时。

思路2

根据提示,并且数组已经升序排列,我们容易想到使用二分查找,即从头遍历,a[i],然后在剩下的里边中数组去找target - a[i]。此时的时间复杂度为O(nlogn)。相比思路1,时间复杂度有所优化

思路3

采用双指针法

假设数组为a

1,定义指针index1和index2。值分别为index1 = 0,index2 = a.size()-1。

2,如果a[index1]+a[index2] > target。那么此时,index2应该向左移动一位,即减一。(注:因为升序排列,index2向左移动,那么两者之和会减小)

如果a[index1]+a[index2] < target。那么此时,index1应该向右移动一位。即加一。

4,直到找到两个值,或者index1 >= index2时结束。

代码2

该代理是思路2的代码
class Solution {
public:
int binary_serach(vector<int>&num ,int t,int index1){
int res = -1;
int start = 0;
int end = num.size()-1;
while(start <= end){
int mid = start + (end-start)/2;
if(num[mid] ==  t){
if(mid > index1){
res = mid;
break;
}else{
start = mid+1;;
}
}else if(num[mid] > t){
end = mid -1;
}else{
start = mid +1;
}
}
return res;
}

vector<int> twoSum(vector<int>& numbers, int target) {
int index1 = 1;
int index2 = 2;
vector<int> res;
int sum = 0;
for(int i = 0; i < numbers.size(); ++i){
int index2 = binary_serach(numbers,target-numbers[i],i);
if(index2 != -1){
res.push_back(i+1);
res.push_back(index2+1);
break;
}
}
return res;
}
};


代码3

class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int index1 = 0;
int index2 = numbers.size()-1;
int sum = 0;
vector<int> res;
while(index1 < index2){
sum = numbers[index1] + numbers[index2];
if(sum == target){
break;
}else if(sum > target){
index2--;
}else{
index1++;
}
}
res.push_back(index1+1);
res.push_back(index2+1);

return res;
}
};


总结

1,当遇到已经排序好的数组,应该立即联想到二分法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: