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, and you may not use thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
一道非常简单的问题,过AC很容易,先上代码。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i<nums.size(); i++)
{
for(int j = i+1; j<nums.size(); j++)
{
if(nums.at(i)+nums.at(j) == target)
{
vector<int> output;
output.push_back(i);
output.push_back(j);
return output;
}
}
}
}
};
Runtime在200ms开外,并不是非常的理想。因为代码运行在O(n^2)的时间复杂度上。
在看了几个大神的操作之后,使用unordered_map,改进到O(n)上看看如何。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector <int> output;
unordered_map <int, int> hash_table;
for(int i = 0; i<nums.size(); i++)
{
int numNeed = target - nums.at(i);
if(hash_table.find(numNeed)!=hash_table.end())
{
output.push_back(hash_table[numNeed]);
output.push_back(i);
return output;
}
else
{
hash_table[nums.at(i)] = i;
}
}
}
};
平均跑完test case的Runtime降到9ms。
另一个思路一样的实现,修改自于Angel1a的代码,runtime进一步降到6ms。原因应该是unordered_map还是有些冗余。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int MAX = 99999;
int DELT = 49999;
vector<int> ans;
int x[MAX];
memset(x, 0, sizeof(x));
for (int i = 0; i < nums.size(); i++)
{
if (x[nums[i] + DELT])
{
ans.push_back((x[nums[i] + DELT] - 1));
ans.push_back(i);
return ans;
}
x[target - nums[i] + DELT] = i + 1;
}
}
};