当前位置:网站首页>力扣题(1)—— 两数之和
力扣题(1)—— 两数之和
2022-07-28 08:30:00 【世界的隐喻】
两数之和
题目内容
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例
示例 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.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
*只会存在一个有效答案*
进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/two-sum
题解
题解一:双循环暴力解法
看到这个题目的第一反应就是双循环解法。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(0, length):
for j in range(i+1, length): # 因为一定有答案,不用考虑第二层循环的边界问题,即 i+1 一定不会等于 length
if nums[i] + nums[j] == target:
return [i, j]
很显然,因为是双循环暴力解法,所以在力扣上通过的时间比较长,大概是 3344 ms
题解二:双循环解法进阶版
第一种题解的双循环是无脑的双循环,根本不判断是否有必要双循环——比如说是否有数字和第一层循环的数字相加等于我们的目标数字。
所以在进阶版中我们需要做的就是在进行第二层循环前加一层判断判断是否有必要进行第二层循环。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(0, length):
if (target - nums[i]) in nums: # 判断是否有必要进行第二层循环
for j in range(i+1, length):
if nums[j] + nums[i] == target:
return [i, j]
力扣通过的时间大约是728 ms
题解三:利用 python 函数 index
不进行双循环直接查找 target - nums[i]数字在列表中的位置
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0, len(nums)):
num1 = target - nums[i]
if num1 in nums: # 判断 target - nums[i] 是否在列表中
j = nums.index(num1)
if j != i: # 判断定位到的数字位置是否和第一次循环数字位置一致
return [i, j]
力扣通过的时间大约是724 ms
题解四:字典模拟哈希表
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {
} # 字典 key 值记录数字,value 记录下标,因为只有一个答案,不用考虑数字相同的情况而造成的覆盖导致答案不全的问题
for i in range(0, len(nums)):
num1 = target - nums[i]
if num1 in dic: # 判断数字是否存在于 字典中
return [dic.get(num1), i]
dic[nums[i]] = i # 记录数字和下标
力扣通过的时间大约是40 ms
边栏推荐
- 478-82(56、128、718、129)
- [activity registration] User Group Xi'an - empowering enterprise growth with modern data architecture
- After reading these 12 interview questions, the new media operation post is yours
- Kubernetes technology and Architecture (VII)
- CSV file storage
- Post it notes -- 45 {packaging of the uniapp component picker, for data transmission and processing -- Based on the from custom packaging that will be released later}
- mysql主从架构 ,主库挂掉重启后,从库怎么自动连接主库
- Sentry log management system installation and use tutorial
- Do you know the five minute rule and the ten byte rule?
- 2022年安全员-B证考试模拟100题及答案
猜你喜欢

TXT text file storage

Machine learning: self paced and fine tuning

Implementation principle of golang synergy

c语言数组指针和指针数组辨析,浅析内存泄漏
![[English postgraduate entrance examination vocabulary training camp] day 15 - analyze, general, avoid, surveillance, compared](/img/a8/2c2fab613035f5e50524056d5f51a3.png)
[English postgraduate entrance examination vocabulary training camp] day 15 - analyze, general, avoid, surveillance, compared

Go waitgroup and defer
![Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]](/img/97/6c3662ef36b02bc42eec95abaa6bc5.png)
Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]

站在大佬的肩膀上,你可以看的更远

XMIND Zen installation tutorial

Learn to draw with nature communications -- complex violin drawing
随机推荐
Will sqlserver CDC 2.2 generate table locks when extracting large tables from the source
App加速读取显示IPFS图片的解决方案和实现
Learn to draw with nature communications -- complex violin drawing
[592. Fraction addition and subtraction]
I use SqlClient normally, and dlink submission will report this error. What should I do?
linux初始化mysql时报错 FATAL ERROR: Could not find my-default.cnf
After reading these 12 interview questions, the new media operation post is yours
Basic syntax of jquey
象棋机器人夹伤7岁男孩手指,软件测试工程师的锅?我笑了。。。
Completion report of communication software development and Application
Eight ways to solve EMC and EMI conducted interference
51单片机存储篇:EEPROM(I2C)
C#简单调用FMU ,进行仿真计算
[English postgraduate entrance examination vocabulary training camp] day 15 - analyze, general, avoid, surveillance, compared
中国地图省>市>级>区>镇>村5级联动下载【2019和2021】
01-TensorFlow计算模型(一)——计算图
训练一个自己的分类 | 【包教包会,数据都准备好了】
You're not still using xshell, are you? This open source terminal tool is yyds!
阿里云服务器搭建和宝塔面板连接
Mongodb (compare relational database, cloud database, common command line, tutorial)