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