当前位置:网站首页>代码随想录笔记_哈希_1l两数之和
代码随想录笔记_哈希_1l两数之和
2022-07-30 14:59:00 【Erik_Won】
代码随想录二刷笔记记录
LC1.两数之和
题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
思路分析
map解法思路
map记录数值和下标 map(nums[i],index)
如果 target - nums[i] 在 map 中,则取出其下标
代码实现
完整代码实现
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if (nums == null || nums.length == 1) return res;
Map<Integer,Integer> map = new HashMap<>();
//建立索引
for (int i = 0; i < nums.length; i++) {
map.put(nums[i],i);
}
//遍历寻找两数之和
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];//数1:temp , 数2 nums[i]
//如果 temp 存在 map 中,则 temp 和 nums[i] 之和必为 target
if (map.containsKey(temp)){
res[0] = i;
res[1] = map.get(temp);
break;
}
}
//建立索引和遍历也可以合并,如下
// for (int i = 0; i < nums.length; i++) {
// int temp = target - nums[i];
// if (map.containsKey(temp)){
// res[0] = i;
// res[1] = map.get(temp);
// break;
// }
// map.put(nums[i],i);
// }
return res;
}
边栏推荐
- Example of video switching playback (video switching example) code
- About the data synchronization delay of MySQL master-slave replication
- 如何写一份高可读性的软件工程设计文档
- L2-007 家庭房产(vector、set、map的使用)
- golang modules initialization project
- Lock wait timeout exceeded solution
- Mysql数据库查询好慢,除了索引,还能因为什么?
- How to split microservices?
- tiup install
- 延时消息队列
猜你喜欢

481-82(105、24、82、34、153)

我们公司用了 6 年的网关服务,动态路由、鉴权、限流等都有,稳的一批!

golang modules initialization project

JVM performance tuning

ISELED---氛围灯方案的新选择

哨兵

如何写一份高可读性的软件工程设计文档

Back waves are coming!Ali produced the "second generation" container technical manual and brain map, which is too fragrant

Flink实时仓库-DWS层(关键词搜索分析-自定义函数,窗口操作,FlinkSql设置水位线,保存数据到Clickhouse)模板代码

yarn的安装及使用教程
随机推荐
R中按照数字大小进行排序
90后人大硕士为学医竟重新高考,成功被首医大录取
Redis cache penetration, breakdown, avalanche and consistency issues
软件包 - 笔记
被捧上天的Scrum敏捷管理为何不受大厂欢迎了?
本地事务与分布式事务
【为宏正名】99%的人从第一天学习C语言就自废的武功
(科普文)什么是碎片化NFT(Fractional NFT)
Core Topics under Microservice Architecture (2): Design Principles and Core Topics of Microservice Architecture
Mysql database query is very slow. Besides the index, what else can be caused?
让人上瘾的新一代开发神器,彻底告别Controller、Service、Dao等方法
Memory-mapped, bit-band operations
哨兵
【喂到嘴边了的模块】准备徒手撸GUI?用Arm-2D三分钟就够了
我们公司用了 6 年的网关服务,动态路由、鉴权、限流等都有,稳的一批!
编译、链接 - 笔记 - 3
Packages - Notes
localhost with 127.0.0.1
yarn的安装及使用教程
JHM:芳环羟化双加氧酶数据库DARHD建立及相关引物评价