当前位置:网站首页>【刷题记录】1. 两数之和
【刷题记录】1. 两数之和
2022-07-05 20:21:00 【InfoQ】
前言
一、题目描述
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
输入: nums = [3,2,4], target = 6
输出: [1,2]
1 <= s.length <= 1000
s
由英文字母(小写和大写)、','
和 '.'
组成
1 <= numRows <= 1000
二、思路分析:
1.简单直接暴力解法 - 遍历
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
//保证num[j]存在 i 遍历到 n-2 为止
for (int i = 0; i < length - 1; i++) {
//避免重复,遍历从当前数组后面开始
for (int j = i + 1; j < length; j++) {
if (nums[i] + nums[j] == target) return new int[]{i,j};
}
}
return new int[]{};
}
}

2.改进下解法-哈希表
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) return new int[]{map.get(target - nums[i]), i};
map.put(nums[i], i);
}
return new int[]{};
}
}

总结
边栏推荐
- 信息学奥赛一本通 1338:【例3-3】医院设置 | 洛谷 P1364 医院设置
- Leetcode(695)——岛屿的最大面积
- What is PyC file
- Convolution free backbone network: Pyramid transformer to improve the accuracy of target detection / segmentation and other tasks (with source code)
- Go language learning tutorial (16)
- 鸿蒙系统控制LED的实现方法之经典
- July 4, 2022 - July 10, 2022 (UE4 video tutorial MySQL)
- Schema and model
- - Oui. Net Distributed Transaction and Landing Solution
- 点云文件的.dat文件读取保存
猜你喜欢
物联网智能家居基本方法实现之经典
JS implementation prohibits web page zooming (ctrl+ mouse, +, - zooming effective pro test)
Leetcode skimming: binary tree 16 (path sum)
Practical demonstration: how can the production research team efficiently build the requirements workflow?
Guidelines for application of Shenzhen green and low carbon industry support plan in 2023
[quick start to digital IC Verification] 8. Typical circuits in digital ICs and their corresponding Verilog description methods
微信小程序正则表达式提取链接
leetcode刷题:二叉树14(左叶子之和)
leetcode刷题:二叉树15(找树左下角的值)
Oracle tablespace management
随机推荐
sort和投影
小程序页面导航
sun.misc.BASE64Encoder报错解决方法[通俗易懂]
Rainbond 5.7.1 支持对接多家公有云和集群异常报警
. Net distributed transaction and landing solution
信息学奥赛一本通 1338:【例3-3】医院设置 | 洛谷 P1364 医院设置
leetcode刷题:二叉树17(从中序与后序遍历序列构造二叉树)
无卷积骨干网络:金字塔Transformer,提升目标检测/分割等任务精度(附源代码)...
【数字IC验证快速入门】1、浅谈数字IC验证,了解专栏内容,明确学习目标
[quick start of Digital IC Verification] 6. Quick start of questasim (taking the design and verification of full adder as an example)
基础篇——配置文件解析
Relationship between mongodb documents
.Net分布式事务及落地解决方案
nprogress插件 进度条
Go language | 01 wsl+vscode environment construction pit avoidance Guide
Dry goods navigation in this quarter | Q2 2022
PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
港股将迎“最牛十元店“,名创优品能借IPO突围?
Leetcode brush questions: binary tree 18 (largest binary tree)
Y57. Chapter III kubernetes from entry to proficiency -- business image version upgrade and rollback (30)