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

Public Key Retrieval is not allowed error solution

MySQL详细学习教程(建议收藏)

php how to query string occurrence position

Nervegrowold d2l (7) kaggle housing forecast model, numerical stability and the initialization and activation function

《痞子衡嵌入式半月刊》 第 59 期

Discuz杂志/新闻报道模板(jeavi_line)UTF8-GBK模板

Rounding out the most practical way of several DLL injection

数组和指针(2)

.NET 6.0中使用Identity框架实现JWT身份认证与授权

DTSE Tech Talk丨第2期:1小时深度解读SaaS应用系统设计
随机推荐
MySQL详细学习教程(建议收藏)
The service already exists! Solution
[flutter] What is MaterialApp and Material design
基于STM32F407使用ADC采集电压实验
绕开驱动层检测的无痕注入
C语言学习之旅 【函数(二)】
Leetcode 118. 杨辉三角
Minio 入门
大厂高管借钱炒股,亏到破产卖房。。。
@Bean注解详解
【HMS core】【FAQ】A collection of typical questions about Account, IAP, Location Kit and HarmonyOS 1
疫情之下的裁员浪潮,7点建议帮你斩获心仪offer
No qualifying bean of type问题解决
Lotus 1.16.0 minimum snapshot export import
huato 热更新环境搭建(DLL方式热更新C#代码)
大厂面试官眼中的好简历到底长啥样
data storage
【Linux操作系统】 虚拟文件系统 | 文件缓存
MySQL超详细安装教程 手把手教你安装MySQL到使用MySQL 最简单的MySQL安装方式,这种方式装,卸载也简单
为人处世之道,与君共勉!