1. The sum of two numbers
Idea 1: Violent traversal [o(n^2)]
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for (int i = 0; i < nums.size(); i++)
{
for (size_t j = i+1; j < nums.size(); j++)
{
/* code */
if(nums[j]==target-nums[i])//keypoint
{
res.push_back(i);
res.push_back(j);
}
}
}
return res;
}
};
Idea 2: The key point of using a hash table [o(n)]
is to use map as hash storage. Compared with the violent 2 cycles, it is replaced with o(1) in the second cycle.
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int,int> mapT;
for (int i = 0; i < nums.size(); i++)
{
unordered_map<int,int>::iterator iter=mapT.find(target-nums[i]);
if(iter!=mapT.end())
{
res.push_back(iter->second);
res.push_back(i);
}
else
{
mapT.insert(pair<int,int>(nums[i],i));//keypoint
}
}
return res;
}
};