您的位置:首页 > 其它

【LeetCode】167. Two Sum II - Input array is sorted

2017-08-25 14:07 537 查看
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 and you may not use the same element twice.

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

Output: index1=1, index2=2

方法一使用二分查找,时间复杂度为nlogn

class Solution {
public:
int find(vector<int>& a,int num){
int l=0,r=a.size()-1;
int mid=(l+r)/2;
while(l<=r){
mid=(l+r)/2;
if(a[mid]==num){
return mid;
}else if(a[mid]>num){
r=mid-1;
}else{
l=mid+1;
}
}
return -1;
}
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ans;
for(int i=0;i<numbers.size();i++){
int index=find(numbers,target-numbers[i]);
if(index!=-1&&index!=i){
ans.push_back(i+1);
ans.push_back(index+1);
break;
}
}
if(ans[0]>ans[1])swap(ans[0],ans[1]);
return ans;
}
};


方法2:使用头尾两个指针,一次遍历,0(N)时间复杂度即可。

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

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: