what is “two sum” problem?
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。
solution1: Brute Force蛮力法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> res;
for(int i=0;i<(nums.size()-1);i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
{
res.push_back(i);
res.push_back(j);
break;
}
}
}
return res;
}
};
Time complexity : O(n^2) ,Space complexity : O(1)
solution2:Hash Table哈希表
What is the best way to maintain a mapping of each element in the array to its index? A hash table.哈希表是获取数组中某个指定元素的索引的最好方法。
We reduce the look up time from O(n)O(n) to O(1)O(1) by trading space for speed. 通过增加空间消耗来较少时间消耗。
Beware that the complement must not be nums[i]nums[i] itself!注意获取的另一个元素不能和第一个元素是同一个数。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
map<int, int> m;
vector<int>res;
for (int i = 0; i < nums.size(); i++)
{
pair<int, int> p(nums[i], i);
m.insert(p);
}
for (int i = 0; i < nums.size(); i++)
{
int complement = target - nums[i];
if (m.count(complement) &&((m.find(complement)->second)!=i))
{
res.push_back(i);
res.push_back((m.find(complement)->second));
break;
}
}
return res;
}
};
注意:map.count()和map.find()的区别:map.count()是判断hash表中存不存在某个值,如果存在返回1,反之为0。map.find()是返回指向这个值的指针,可以通过指针访问对应的键值。
Time complexity : O(n) ,Space complexity : O(n)
solution3:优化solution2
通过改变给map赋初值的顺序,可以有效回避返回两个元素相同的情况。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>res;
map<int, int> m;
for (int i = 0; i < nums.size(); i++)
{
int complement = target - nums[i];
if (m.count(complement))
{
res.push_back(m.find(complement)->second);
res.push_back(i);
return res;
}
pair<int, int> p(nums[i], i);
m.insert(p);
}
return res;
}
};
Time complexity : O(n) ,Space complexity : O(n)