您的位置:首页 > 其它

Two Sum--leetcode

2017-06-05 20:00 381 查看
题目描述:

解题思路:如果用暴力求解法,则只需要两层for循环,当数组规模较小时,时间可以接受,当数组规模庞大时,时间复杂度为O(N2);系统会提示times limits.所以在这里采用的是hash table,具体的代码如下class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
vector<int> ret;
for(int i=0;i<nums.size();i++){
int numbertofind=target-nums[i];
if(hash.find(numbertofind)!=hash.end()){
ret.push_back(hash[numbertofind]);
ret.push_back(i);
return ret;
}
hash[nums[i]]=i;
}
return ret;
}
};思路:利用数组值作为hash的键值,对应的索引为相应的value,对数组中的每一个数计算numsToFind=target-nums[i]; 查找hash表是否存在numsToFind,如存在,则将两者的索引存到ret中,直接返回即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hash