leetcode上easy的一道题。
用cpp跑了两种算法。
1.先将拷贝一份vector。对新的数组排序,并找出相加等于target的对应值first、second。再在原始数组中扫一遍,找出first和second的相应位置。代码如下。
1 | class Solution { |
结果:9ms,超过96.22%。
2.使用map,存储<数值,数值的位置>。遍历整个数组。遍历过程中,其中map中key存储target-已遍历元素的值,value存储已遍历元素的位置。如果下一个元素在map中可以找到相应的key,则满足条件;如果下一个元素找不到相应的key,就将1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> m;
vector<int> rst;
auto it = nums.begin();
size_t i = 0;
for(;it != nums.end(); it++,i++)
{
auto find_it = m.find(*it);
if(find_it == m.end())
{
m.insert(pair<int,int>(target-*it,i));
}
else
{
rst.push_back(find_it->second);
rst.push_back(i);
}
}
return rst;
}
};
结果:19ms,超过58.82%。这里使用了unordered_map,要比使用map快(29ms)。unordered_map是基于hash实现的,map是基于tree实现的。