当前位置:网站首页>牛客网:两数之和
牛客网:两数之和
2022-06-10 16:42:00 【lsgoose】


这题我看到第一反应是做个pair,放数字和索引。然后对数字进行排序,然后双指针。
原来还有哈希表这么神奇的东西。于是我们可以用一个哈希表存储值和索引。
思路如下:
对整个数组遍历:
1.对当前数求补得temp
2.temp不在哈希表中,则将当前数和其索引放入哈希表
3.否则,找到两个数,将索引加1的标号放入答案,结束
class Solution {
public:
/**
*
* @param numbers int整型vector
* @param target int整型
* @return int整型vector
*/
vector<int> twoSum(vector<int>& numbers, int target) {
// write code here
vector<int> res;
unordered_map<int, int> hash;
for(int i=0;i<numbers.size();++i){
int temp=target-numbers[i];
if(hash.find(temp)==hash.end()){
hash[numbers[i]]=i;
}else{
res.push_back(hash[temp]+1);
res.push_back(i+1);
break;
}
}
return res;
}
};边栏推荐
- Photoshop如何打开、编辑和导出Webp格式图片的方法
- Solve the problem that idea is stuck in opening a project
- Detailed derivation of perspective projection transformation and related applications
- KDD 2021 | MoCL:利用多层次领域知识的分子图对比学习
- 使用KuboardSpray安装kubernetes(v1.23.1)
- script 标签自带的属性
- Fabric. JS zoom canvas
- 聊聊消息中间件(1),AMQP那些事儿
- Swift 3pThread tool Promise Pipeline Master/Slave Serial Thread confinement Serial queue
- 2022年茶艺师(中级)操作证考试题库及模拟考试
猜你喜欢

Take you to a preliminary understanding of the basic mechanism of classes and objects

A few misunderstandings about programmers are very harmful!

二十多年了,安全套市场还只有杜蕾斯、冈本、杰士邦

Thread interview related questions

Web3最全搞钱秘籍,看这一篇就够了

Smart Scenic Spot Video Monitoring 5G Smart lamp Gateway Network Integrated pole

vscode常用插件与配置

ADB is not an internal or external command, nor is it a runnable program or batch file

Swing visualization plug-in jformdesigner of idea
Redis operation set, Zset, hash data types and use of visualization tools
随机推荐
ahk常用函数
消除业务代码中if....else的五种方式
Example analysis of SQL injection error reporting
复利最高的保险产品是什么?一年要交多少钱?
Cannot locate a 64-bit Oracle Client library:The specified module could not be found.
当v-if和v-for需要同时使用的时候
[the second revolution of report tools] optimize report structure and improve report operation performance based on SPL language
Fabric. JS lock the background image, not affected by zooming and dragging
自定义视图:图形与图像的处理(一):使用简单图片
Designing drugs with code: are we here yet?
Only three steps are needed to learn how to use low code thingjs to connect with Sen data Dix data
IDEA的Swing可视化插件JFormDesigner
Richard Behrman, the founder of dynamic planning
Installing kubernetes using kuboardspray (v1.23.1)
web集群基础知识学习(1)
Fabric.js 元素被选中时保持原有层级
Nat. Commun. | 用于加速发现抗生素抗性基因的知识整合和决策支持
[play with Huawei cloud] Kunpeng devkit migration practice
Cap version 6.1 Release Notice
SOA架构/测试阶段接口描述语言转换方案