当前位置:网站首页>每日一题:两数之和
每日一题:两数之和
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;
}
}边栏推荐
猜你喜欢

【HMS core】【FAQ】A collection of typical questions about Account, IAP, Location Kit and HarmonyOS 1

How to remove first character from php string

SMI 与 Gateway API 的 GAMMA 倡议意味着什么?

详解最实用的几种dll注入方式

完美绕开CRC32检测的无痕hook

3D激光SLAM:LeGO-LOAM论文解读---激光雷达里程计与建图

23. Please talk about the difference between IO synchronization, asynchronous, blocking and non-blocking

go 学习03 基础知识变量类型

华为云数据治理生产线DataArts,让“数据‘慧’说话”

全职做自媒体靠谱吗?
随机推荐
论文阅读 (63):Get To The Point: Summarization with Pointer-Generator Networks
Visual Studio 集成Qt开发环境的一些注意事项
Chapter 5 Advanced SQL Processing
绕开驱动层检测的无痕注入
win下搭建php环境的方法
华为云数据治理生产线DataArts,让“数据‘慧’说话”
华为云WeLink携手伙伴,共建协同办公生态
游戏多开检测的几种实现方法及破解方法参考
如何写一份高可读性的软件工程设计文档
3D激光SLAM:LeGO-LOAM论文解读---激光雷达里程计与建图
SMI 与 Gateway API 的 GAMMA 倡议意味着什么?
PHP留言反馈管理系统源码
Is it reliable to work full-time in self-media?
Leetcode 118. Yanghui Triangle
探究CSAPP实验二-bomb lab-第一节
【Linux操作系统】 虚拟文件系统 | 文件缓存
Scheduling_Channel_Access_Based_on_Target_Wake_Time_Mechanism_in_802.11ax_WLANs
node.js中怎么连接redis?
打印1-100之间的奇数
全职做自媒体靠谱吗?