您的位置:首页 > 其它

LeetCode two sum

2017-06-03 11:29 495 查看

two sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the
same element twice.

找到一个数组里面和为给定的数的两个元素的指针。最简单地方法当然就是两层循环(N*2)代码如下
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i=0;i<nums.size();i++){
for(int j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
result.push_back(i);
result.push_back(j);
}
}
}
return result;
}
};

在评论中看到了复杂度(N)的算法,用到了hashtable
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
vector<int> result;
for(int i=0;i<nums.size();i++){
int numtofind=target-nums[i];
if(hash.find(numtofind)!=hash.end()){
result.push_back(hash[numtofind]);
result.push_back(i);
}
hash[nums[i]]=i;
}
return result;
}
};
之所以在循环内部插入键值对是为了避免结果重复
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: