您的位置:首页 > 其它

Two sum(在数组中找两个数,使其和为指定值)

2015-05-31 17:08 393 查看
Given an array of integers, 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

Hide Tags
 Array Hash
Table

Solutions:

1)最直接的O(N^2)的算法,再leetCode上超时。

2)先将数组排序,再从两端向中间查找,因为有可能有相等的元素,所以找第二个数的位置时要从高端开始。

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v=nums;
sort(v.begin(), v.end());
int l=0, r=v.size()-1;
while(l<r){
if(v[l]+v[r]>target) {
--r;
}
else if(v[l]+v[r]<target) {
++l;
}
else{
break;
}
}
int i=0;
for(i=0; i<nums.size(); ++i) {
if(nums[i] == v[l]) {
l=i+1;
break;
}
}
for(i=nums.size()-1; i>=0; --i) {
if(nums[i] == v[r]) {
r=i+1;
break;
}
}
vector<int> ret;
if(l>r){
swap(l, r);
}
ret.push_back(l);
ret.push_back(r);
return ret;
}
};


3)用一个map<int, int>存储已经遍历过的数,键为数,值为位置(从1开始)。遍历到某数x,若target-x已经被遍历过,则此2数即为所求。

但其时间反而比上面的要长。

class Solution{
public:
vector<int> twoSum(vector<int> &nums, int target) {
map<int, int> m;
int l=0, r=0;
for(l=0; l<nums.size(); ++l) {
if((r=m[target- nums[l]]) != 0) {
break;
}
m[nums[l]]=l+1;
}
l+=1;
if(l>r) {
swap(l, r);
}
vector<int> ret;
ret.push_back(l);
ret.push_back(r);
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: