深入解析:【Python刷力扣hot100】1. Two Sum

问题

给定一个整数数组 nums 和一个整数 target,返回两个数的索引,使得这两个数相加等于 target。

Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]

Example 3:
Input: nums = [3,3], target = 6 Output: [0,1]

解1:暴力搜索

遍历所有情况,找到解就return。

时间复杂度 O ( n 2 ) O(n^2) O(n2):最多需要比较 n × ( n − 1 ) 2 \frac{n \times (n-1)}{2} 2n×(n1)

空间复杂度 O ( 1 ) O(1) O(1):随着数组规模的增大,我们使用的额外空间是不变的。

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
ans = []
n=len(nums)
# i:起点。j:终点
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
ans.append(i), ans.append(j)
return ans
return ans
# 可以用点语法糖简化
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
ans = []
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i,j]
return []

解2:哈希表

利用哈希表,把已经用过的数字存储起来,再次使用时可用哈希表立即访问(时间复杂度为 O ( 1 ) O(1) O(1)),空间换时间。

时间复杂度 O ( n ) O(n) O(n):最坏情况下需要遍历列表,而列表的长度为 n n n

空间复杂度 O ( n ) O(n) O(n):随着数组规模的增大,我们需要的哈希表长度也等比增加,哈希表最多需要储存数组内的所有元素。

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable=dict()
for i,num in enumerate(nums):
if target-num in hashtable:
return [hashtable[target-num],i]
hashtable[num]=i # 看过后发现解没出现,就存入哈希表
return []

参考

https://leetcode.cn/problems/two-sum

posted on 2025-10-28 09:08  wgwyanfs  阅读(1)  评论(0)    收藏  举报

导航