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

LeetCode | 1) Two sum

2016-10-02 15:51 260 查看

题目

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
};
}


思路

方案 1:两次循环遍历整个数组,检测
nums[i] + nums[j] == target
,时间复杂度O(N2)

方案 2:首先利用
map<int, size_t>
将数据和对应的下标存储起来;然后一次遍历数组,在hash map中查找
tartget - nums[i]
,时间复杂度是O(n)∗O(1)=O(N). 该方法需要两次hash,一次是建立hash表,另一次是查找hash表,存在有可能找到的数和num[i]一样这个问题

方案 3:只用一遍hash表。首先查找hash表中是否存在
nums[i]
,不存在则将
target - nums[i]
存储在hash表中。

代码

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> vec;
unordered_multimap<int, size_t> numMap;
//元素之间没有序关系,宜用unordered_map; nums数组中有多个同样的数,宜用multimap
//综合考虑,使用unordered_multimap

for (size_t it = 0; it != nums.size(); ++it)
{
auto iter = numMap.find(nums[it]);//先对numMap进行查找
if (iter == numMap.end())
{
numMap.insert({target - nums[it], it});//没有找到则插入数据和下标
}
else
{
return vector<int>{iter->second, it};
//找到,直接返回numMap的迭代器iter指向的下标(iter->second)和当前nums的下标it。
}
}
return vec;
}
};


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