当前位置:网站首页>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]; //返回异常或空
}
}
边栏推荐
- DFS's complement to pruning
- 【开发者必看】【push kit】推送服务服务典型问题合集2
- Flink state
- Interface testing framework of actual combat (2) | interface request assertion
- 接口和协议
- typescript43-类型兼容性说明
- 接口测试框架实战 | 流程封装与基于加密接口的测试用例设计
- Two ways to simulate multi-user login in Jmeter
- rosbag工具plotjuggler无法打开rosbag的问题
- Concepts and Methods of Exploratory Testing
猜你喜欢
Windows 安装PostgreSQL
UV 裂解的生物素-PEG2-叠氮|CAS:1192802-98-4生物素接头
PotPlayer实现上班摸鱼电视自由
刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
typescript49-交叉类型
DFS's complement to pruning
Modified BiotinDIAZO-Biotin-PEG3-DBCO|diazo-biotin-tripolyethylene glycol-diphenylcyclooctyne
接口和抽象
Kotlin-Flow常用封装类:StateFlow的使用
How to prepare for the test interface test data
随机推荐
High availability, two locations and three centers
User password verification
WinForm的控件二次开发
数字化时代,企业如何建立自身的云平台与商业模式的选择?
内部类、static关键字、final
Common lipophilic cell membrane dyes DiO, Dil, DiR, Did spectrograms and experimental procedures
建立树形结构
WebSocket的实际应用
【 Harmony OS 】 【 ano UI 】 lightweight data storage
Shell之条件语句
Kotlin-Flow common encapsulation class: the use of StateFlow
【Harmony OS】【ARK UI】ets使用startAbility或startAbilityForResult方式调起Ability
索引创建、删除与使用
Tributyl-mercaptophosphane "tBuBrettPhos Pd(allyl)" OTf), 1798782-17-8
C#异步和多线程
DFS's complement to pruning
Detailed explanation of MOSN reverse channel
获取Ip工具类
Talking about GIS Data (6) - Projected Coordinate System
阿里云对象存储oss私有桶生成链接