博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1. Two Sum
阅读量:4259 次
发布时间:2019-05-26

本文共 833 字,大约阅读时间需要 2 分钟。

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].

思路:用一个hash表存储每个元素及其相应的index,并在数组中进行循环查找

vector
twoSum(vector
& nums, int target) { if (nums.size() <= 1)return vector
{}; unordered_map
res; vector
idx; for (int i = 0; i < nums.size(); i++)res[nums[i]] = i; for (int i = 0; i < nums.size(); i++){ int tmp = target - nums[i]; if (res.find(tmp) != res.end() && res[tmp] > i){ idx.push_back(i), idx.push_back(res[tmp]); return idx; } } return idx;}

转载地址:http://yaxei.baihongyu.com/

你可能感兴趣的文章
Java基础入门(三)
查看>>
Java基础入门(四)
查看>>
Java基础入门(十)
查看>>
Java基础入门(完结篇)
查看>>
Java进阶之面向对象(一)——继承
查看>>
Java进阶之自定义ArrayList&斗地主发牌案例
查看>>
JavaWeb之filter&listener&文件上传
查看>>
JavaWeb之Ajax&json
查看>>
BUFG,IBUFG,BUFGP,IBUFGDS等含义以及使用
查看>>
转载:在 Windows 10 下遇到移动硬盘不自动分配盘符的问题
查看>>
DDR2 SSTL_18标准
查看>>
DDR3的DQS_p/n信号电平摆幅变化不一致现象
查看>>
北大旁听生中的历史名人
查看>>
大唐凌烟阁开国廿四将
查看>>
Access数据库出现"Selected collating sequence not supported by the operating system."错误
查看>>
逻辑思维测试题
查看>>
如何用Easy CHM制作CHM格式电子书(帮助文档)
查看>>
为什么学习python
查看>>
华为进不了美国,并不是贸易保护这么简单
查看>>
markdown文件的基本常用编写语法(图文并茂)
查看>>