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