当前位置:网站首页>1. 两数之和
1. 两数之和
2022-08-03 05:09:00 【破烂摆烂人】
LeetCode 1. 两数之和
方法一:暴力枚举
思路:枚举在数组中所有的不同的两个下标的组合,逐个检查他们所对应的数的和是否等于target
public class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length; //数组长度
for(int i=0;i<len-1;i++){
//注意len-1
for(int j=i+1;j<len;j++){
//注意j=i+1,之前的元素不需要再匹配;j<len
if(nums[i]+nums[j]==target){
return new int[]{
i, j}; //返回int[]
}
}
}
return new int[0]; //返回异常或空
}
}
方法二:查找表法-哈希表
思路:数组中的每一个数 x,寻找数组中是否存在 target - x
使用哈希表,可以将寻找 target - x
的时间复杂度降低到从 O(N)降低到 O(1)
创建一个哈希表,对于每一个 x
,首先查询哈希表中是否存在 target - x
,然后将 x
插入到哈希表中,即可保证不会让 x
和自己匹配
public class Solution {
public int[] twoSum(int[] nums, int target) {
/*方法二:查找表法(哈希表)*/
int len = nums.length; //数组长度
HashMap<Integer,Integer> hashMap = new HashMap<>(len-1); //定义哈希表,初始容量
hashMap.put(nums[0],0); //第一个值hash表中没有配对值,直接存放
for(int i=1;i<len;i++){
//注意i=1
int another = target-nums[i]; //获取配对
if(hashMap.containsKey(another)){
//hash表中找到配对值
return new int[]{
hashMap.get(another),i}; //返回i以及配对值的关键字
}
hashMap.put(nums[i], i); //没有配对,存放到哈希表,i+1;
}
return new int[0]; //返回异常或空
}
}
边栏推荐
- 【Harmony OS】【ARK UI】ets使用startAbility或startAbilityForResult方式调起Ability
- MySql 创建索引
- 【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
- IO process thread -> thread -> day5
- 测试人员的价值体现在哪里
- js的垃圾回收机制
- Get the Ip tool class
- 数据库基本概述与SQL概述
- Interface test framework combat (1) | Requests and interface request construction
- Coordinate knowledge in digital twin campus scenarios
猜你喜欢
typescript45-接口之间的兼容性
Alienware上线首个数字时装AR试穿体验
typescript39-class类的可见修饰符
测试人员的价值体现在哪里
在线密码生成工具推荐
【生物素叠氮化物|cas:908007-17-0】价格_厂家
Interface Test Framework Practice (4) | Get Schema Assertion
DDL操作数据库、表、列
How to use the interface management tool YApi?Beautiful, easy to manage, super easy to use
刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
随机推荐
数字孪生园区场景中的坐标知识
【HMS core】【Ads Kit】华为广告——海外应用在国内测试正式广告无法展示
typescript43-类型兼容性说明
【Harmony OS】【ARK UI】Date 基本操作
Install PostgreSQL on Windows
3. 无重复字符的最长子串
用户密码验证
[Fine talk] Using native js to implement todolist
2022/08/02 Study Notes (day22) Multithreading
typescript45-接口之间的兼容性
odps的临时查询能在写sql的时候就给结果一个命名不?
高可用 两地三中心
[Harmony OS] [ARK UI] ETS context basic operations
打破传统电商格局,新型社交电商到底有什么优点?
closures in js
Jmeter 模拟多用户登录的两种方法
DFS's complement to pruning
数据库基本概述与SQL概述
Super handy drawing tool is recommended
GIS数据漫谈(六)— 投影坐标系统