首先介绍一个小技巧,在Markdown编辑器中,如果想使每段开头空两格,则可以在每段开头输入 !   ! ! !每个感叹号改为分号(;),这里因为打成分号的话就看不到命令了所以我替换了一下。
题目: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].
注意:此题明确给出有唯一解,所以一旦得到解就可以结束程序,我因为没注意看题,对答案怀疑了一上午,直到看到别人的一篇博客,哈哈,怪自己喽~
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> m;
vector<int> res;
for(int i=0;i<nums.size();i++)
{
m[nums[i]]=i;
}
for(int i=0;i<nums.size();i++)
{
int t=target-nums[i];
if(m.count(t) && m[t]!=i )
{
res.push_back(i);
res.push_back(m[t]);
break;
}
}
return res;
}
};