当前位置:网站首页>每日一题:两数之和
每日一题:两数之和
2022-07-30 16:41:00 【#小苏打】
思路:
利用哈希表,当判断是否重复,是否有,这种问题一般采用哈希表结构,该题采用map,key为数值,value为下标,(因为我们需要利用key的数值寻找数组的下标), 实则一个tep值,为 target - num[i] 的值,然后到map中需要是否存在符合该值的key,如果有,返回value
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap();
int[] res = new int[2];
if(nums == null||nums.length == 0){
return res;
}
for(int i = 0;i<nums.length;i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[0] = map.get(temp);
res[1] = i;
}
map.put(nums[i],i);
}
return res;
}
}
边栏推荐
猜你喜欢
Horizontal Pod Autoscaler(HPA)
C#西门子S7 协议通过偏移量的方式读写PLC DB块
MySQL详细学习教程(建议收藏)
Wuhan Star Sets Sail: Overseas warehouse infrastructure has become a major tool for cross-border e-commerce companies to go overseas
2022-07-30 Androd 进入深度休眠后把WIFI给关掉,唤醒之后重新打开WIFI
Leetcode 118. 杨辉三角
Mysql进阶优化篇01——四万字详解数据库性能分析工具(深入、全面、详细,收藏备用)
武汉星起航跨境电商有前景吗?亚马逊的未来趋势如何发展?
[NCTF2019] Fake XML cookbook-1|XXE vulnerability|XXE information introduction
如何注册域名、备案以及解析
随机推荐
Large-scale integrated office management system source code (OA+HR+CRM) source code sharing for free
PCIE入门
登录模块调试-软件调试入门
onenote使用
hcip--ospf综合实验
游戏窗口化的逆向分析
win下搭建php环境的方法
云风:不加班、不炫技,把复杂的问题简单化
在 Chrome 浏览器中安装 JSON 显示插件
lotus 1.16.0 最小快照导出 导入
实现web实时消息推送的7种方案
深度学习区分不同种类的图片
Qt 容器控件Tool Box 使用详解
全职做自媒体靠谱吗?
绕开驱动层检测的无痕注入
第5章 SQL高级处理
JVM学习----垃圾回收
How to connect redis in node.js?
Chapter 6: Decisive Autumn Moves
第六章:决胜秋招