当前位置:网站首页>代码随想录笔记_哈希_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;
}
边栏推荐
猜你喜欢

存储器映射、位带操作

Lock wait timeout exceeded解决方案

(Crypto essential dry goods) Detailed analysis of the current NFT trading markets

Excel使用Visual Basic Editor对宏进行修改

yarn安装详细教程说明、升级教程、修改yarn的全局和缓存目录、yarn基本命令

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

Mac 中 MySQL 的安装与卸载

嵌入式开发:嵌入式基础知识——正确启动固件项目的 10 条建议

How is the B+ tree index page size determined?

HTTP缓存小结
随机推荐
Sleuth+Zipkin(可视化) 服务链路追踪
阿里CTO程立:阿里巴巴的开源历程、理念和实践
GeoServer
golang modules initialization project
yarn安装详细教程说明、升级教程、修改yarn的全局和缓存目录、yarn基本命令
Back waves are coming!Ali produced the "second generation" container technical manual and brain map, which is too fragrant
数据库 - 创建数据库、表、函数等
[Cloud native] Alibaba Cloud ARMS business real-time monitoring
Office Automation | Office Software and Edraw MindMaster Shortcuts
How to do a good job in technology selection
Core Topics under Microservice Architecture (2): Design Principles and Core Topics of Microservice Architecture
Flink本地UI运行
[Cloud native] Grayscale release, blue-green release, rolling release, grayscale release explanation
(Popular Science) What is Fractional NFT (Fractional NFT)
华为云重磅发布开源软件治理服务——软件成分分析
Mac 中 MySQL 的安装与卸载
HTTP缓存小结
调试 - 笔记
tiup help
Sentinel