题目介绍

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> hp;
int n = nums.size();
vector<int> res; for(int i=;i<n;i++){ int rest = target - nums[i];
if(hp.find(rest) != hp.end()){
res.push_back(hp[rest]);
res.push_back(i);
return res;
}
hp[nums[i]] = i; // map[key] = value -> map[num] = index;
}
return res;
}
};

补充说明

循环分成三部分:

1.  剩下的 = 目标 - 现在的

2. 检查剩下的是否在map里,在的话,就说明是数组里面的数字,可以返回index了。

3. 将该数字存入map中

有一些要特别注意的是:

map[ key ] = value -> map[num] = index ,以数字为key, 以存入的内容为index。所以,搜索的时候,以key(即数字)为依据,而 index 为我们要的结果。

最新文章

  1. [LeetCode] All solution
  2. C# 将绝对路径转换为相对路径
  3. UOJ261 【NOIP2016】天天爱跑步
  4. servlet生命周期与工作原理
  5. unity awake start 的区别
  6. 设置ASP.NET页面的运行超时时间详细到单个页面及站点
  7. 移动端line-height失效
  8. C#学习7.31判断体重是否超标
  9. Highchart :tooltip工具提示
  10. Node.js事件发射器
  11. java IMAGEIO
  12. Python之collections序列迭代器下标式循环冒泡算法等
  13. 最简单的基于FFmpeg的封装格式处理:视音频复用器(muxer)
  14. 【ODI】| 数据ETL:从零开始使用Oracle ODI完成数据集成(二)
  15. 烽火2640路由器命令行手册-11-IP语音配置命令
  16. IOC,DIP,DI,IoC容器
  17. tensorflow中moving average的用法
  18. centos7配置apache服务
  19. Revit api 创建族并加载到当前项目
  20. Python中struct.pack()和struct.unpack()

热门文章

  1. 数据结构实验之栈与队列五:下一较大值(一)(SDUT 3332)
  2. psexec局域网执行远程命令
  3. vue 中引入第三方js库
  4. REGIONAL SCRUM GATHERING(RSG)2019 CHINA.
  5. Qt pro工程文件介绍
  6. ShapeDrawable
  7. 使用druid连接池带来的坑testOnBorrow=false
  8. 【原创】smarty引擎下的导航按钮高亮实现
  9. qt application logging
  10. XGBoost原理详解