1 Two sum
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 the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
本题的知识点: 可以用hash table来进行快速查找,从而降低时间复杂度
最终提交的代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> indices;
//with hash map
map<int,int> mydict;
for(int i=0;i<nums.size();i++)
{
mydict[nums[i]] = i;
}
for(int i=0;i<nums.size();i++)
{
int res = target - nums[i];
auto it = mydict.find(res);
if(it != mydict.end() && it->second != i)
{
indices.push_back(i);
indices.push_back(it->second);
return indices;
}
}
return indices;
}
};