leetcode最火100题详解笔记——第1题(两数之和)(不断更新补充中)
2021/9/22 23:17:33
本文主要是介绍leetcode最火100题详解笔记——第1题(两数之和)(不断更新补充中),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
leetcode最火100题详解笔记——第1题(两数之和)(不断更新补充中)
- 1.题目
- 2.解决方法
- 3.测试代码
1.题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
注:
1.你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
2.你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2
<
=
nums.
1
ength
<
=
1
0
4
−
1
0
9
<
=
nums
[
i
]
<
=
1
0
9
−
1
0
9
<
=
target
<
=
1
0
9
\begin{aligned} &2<=\text { nums. } 1 \text { ength }<=10^{4} \\ &-10^{9}<=\text { nums }[\mathrm{i}]<=10^{9} \\ &-10^{9}<=\text { target }<=10^{9} \end{aligned}
2<= nums. 1 ength <=104−109<= nums [i]<=109−109<= target <=109
只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
2.解决方法
该部分代码为解决该题目的核心代码,使用两层for循环遍历所有元素
class Solution { public int[] twoSum(int[] nums, int target) { int n = nums.length; for(int i = 0;i < n;i++){ for(int j = i + 1;j < n;j++){ if(nums[i] + nums[j] == target){ return new int[]{i,j}; } } } return new int[0]; } }
3.测试代码
由于 leetcode 只需要完成给出的函数即可,不需要写出输入输出,以及测试代码,所以如果需要自行验证上述核心代码的正确性,可参考下述测试代码
/** * @Description:leetcode HOT 100题刷题笔记——第1题 ——两数之和 * @author 草原一只鹰 * @version 1.0 * @date 2021年9月22日下午10:18:06 * */ public class leedcodeHot1Test{ public static void main(String[] args) { int[] nums = new int[]{2,7,11,15}; int target = 9; Solution test = new Solution(); int[] a = test.twoSum(nums,target); System.out.print("[" + a[0] + "," + a[1] + "]"); } } class Solution { public int[] twoSum(int[] nums, int target) { int n = nums.length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[0]; } }
输出结果:
[0,1]
这篇关于leetcode最火100题详解笔记——第1题(两数之和)(不断更新补充中)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享