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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

思路是循环一次,每次都判断当前数组索引位置的值在不在hashtable里,不在的话,加入进去,key为数值,value为它的索引值;在的话,取得他的key,记为n(此时n一定小于循环变量i),接下来再在hashtable中查找(target-当前数值)这个数,利用了hashtable中查找元素时间为常数的优势,如果找到了就结束,此处需要注意的是,如果数组中有重复的值出现,那么第二次出现时就不会加入到hashtable里了,比如3,4,3,6;target=6时,当循环到第二个3时,也可以得到正确结果。
        最终ac的代码如下:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int > res;
map<int,int> numMap;
map<int,int>::iterator iter;
int len=numbers.size();
for(int i=;i<len;i++)
{
iter=numMap.find(target-numbers[i]);
if(iter!=numMap.end())
{
res.push_back(iter->second);
res.push_back(i);
return res;
}
else
{
numMap[numbers[i]]=i;
}
} }
};

最新文章

  1. Sass初使用
  2. Python3利用BeautifulSoup4批量抓取站点图片的代码
  3. [.net 面向对象程序设计进阶] (4) 正则表达式 (三) 表达式助手
  4. MooseFs-分布式文件系统系列(一)之了解并安装它
  5. docker ui
  6. Android studio 签名使用转
  7. poj 1888 Crossword Answers 模拟题
  8. POJ1037A decorative fence(动态规划+排序计数+好题)
  9. ArcMap - 分割.
  10. CSDN挑战编程——《数学问题》
  11. HDU2196-Computer
  12. python基础:列表生成式和生成器
  13. ORACLE case when then
  14. poj3281(最大流)
  15. WPF中TreeView控件的使用案例
  16. Configuration Error: deployment source &#39;SocietyManage:war exploded&#39; is not valid
  17. android 之TCP客户端编程
  18. AdvStringGrid 标题头 加粗的问题
  19. Android 里的数据储存
  20. Java 中的多线程你只要看这一篇就够了

热门文章

  1. bzoj1878: [SDOI2009]HH的项链(主席树/离线+BIT)
  2. ucenter搭建
  3. Django ORM 查询
  4. java oracle clob string 大字符串存储【转】
  5. 如何更有效使用 Rational AppScan 扫描大型网站,第 1 部分: 工作原理及技术分析
  6. like tp
  7. JS设计模式之装饰者模式
  8. hdu 4903 The only survival
  9. 【BZOJ3769】BST again [DP]
  10. Bzoj4873 [SXOI2017]寿司餐厅