Question:
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.
Solution 1 (brute force)
就是最简单一个一个加过去,用两个for循环,时间复杂度为o(n^2)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n =nums.size();
vector<int> arr; //存储和为target的下标
int k=0;//用来计数
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(nums[i]+nums[j]==target)
{
arr.push_back(i);
arr.push_back(j);
}
}
}
return arr;
}
};
solution2 (hashmap)
这个解法最令我生气的是,好不容易我迈出了把hashmap从理论去实践这一步,但是hashmap却过时了???
呵呵呵呵
变成了unordered_map,unordered_map是key,value形式,但是内部是用哈希表实现的,和map不一样,map是用红黑树实现的
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map <int,int> mp;
//vector<int> ret;
for(int i=0;i<nums.size();i++)
{
if(mp.find(target-nums[i])!=mp.end())
{
return {mp[target-nums[i]],i};
//ret.push_back(i);
//ret.push_back(mp[target-nums[i]]);
}
//mp.insert(pair<int,int>(i,nums[i]));
mp[nums[i]] = i;
}
//return ret;
return { };
}
};
只用一个unorder_map的话就是查找有没有,然后把数据放入mp,不理解的是mp.insert(pair<int,int>(i,nums[i]));这种插入方式会报错,明明这种方式也是合理的。
注释部分是用一个vector的数组来存储符合要求的下标,然后返回数组。