当前位置:网站首页>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]; //返回异常或空
}
}

边栏推荐
猜你喜欢

typescript43-类型兼容性说明

MCM box model modeling method and source analysis of atmospheric O3

Secondary development of WinForm controls

「短视频+社交电商」营销模式爆发式发展,带来的好处有什么?

Harmony OS ets ArkUI 】 【 】 the development basic page layout and data connection

【 Harmony OS 】 【 ano UI 】 lightweight data storage

探索性测试的概念及方法

Tributyl-mercaptophosphane "tBuBrettPhos Pd(allyl)" OTf), 1798782-17-8

接口测试实战| GET/POST 请求区别详解

软件开发的最大的区别是什么?
随机推荐
【Harmony OS】【ARK UI】轻量级数据存储
Modified BiotinDIAZO-Biotin-PEG3-DBCO|diazo-biotin-tripolyethylene glycol-diphenylcyclooctyne
presto安装部署教程
接口测试框架实战(四)| 搞定 Schema 断言
Interface test Mock combat (2) | Combined with jq to complete batch manual Mock
3. 无重复字符的最长子串
Shell条件语句判断
[Developers must see] [push kit] Collection of typical problems of push service service 2
【Harmony OS】【ArkUI】ets开发 图形与动画绘制
MySql 创建索引
typescript46-函数之间的类型兼容性
在竞争白热化的电商行业,链动2+1为什么还有企业在用
用户密码加密工具
DFS's complement to pruning
CAD有生僻字如何打出来、如何提交软件相关问题或建议?
【 Harmony OS 】 【 ano UI 】 lightweight data storage
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
超好用的画图工具推荐
DDL操作数据库、表、列
MOSN 反向通道详解