力扣454.四数相加II、383. 赎金信、15. 三数之和、18. 四数之和
一、力扣454.四数相加II【medium】
题目链接:力扣454.四数相加II
视频链接:代码随想录
1、思路
- 两数之和的拓展
- 将四个数组分成两个数组
- 先对
nums1
和nums2
数组遍历求和,存入字典 - 再对
nums3
和nums4
,寻找字典中是否存在key= -n3 - n4
,对value
计数到count
- 时间复杂度:
O
(
n
2
)
O(n^2)
O(n2)
- 通过将问题分解为两部分(
nums1
和nums2
的和,nums3
和nums4
的和),避免了直接四重循环的高复杂度,时间复杂度为 O ( n 2 ) O(n²) O(n2),其中n
是数组的长度
- 通过将问题分解为两部分(
2、代码
- 使用
defaultdict
"""
哈希表——类似1.两数之和的拓展
使用defaultdict——可以简化代码,特别是在处理需要默认值的场景时,如计数、分组等
时间复杂度:O(n^2)
"""
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap = defaultdict(lambda : 0)
count = 0
for n1 in nums1:
for n2 in nums2:
#避免了手动检查键是否存在或使用 get 方法的额外步骤
hashmap[n1+n2] += 1
for n3 in nums3:
for n4 in nums4:
key = - n3 - n4
count += hashmap.get(- n3 - n4, 0)
return count
- 使用
get
方法检查键是否存在
"""
哈希表——类似1.两数之和的拓展
时间复杂度:O(n^2)
"""
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
#使用 get 方法检查键是否存在
hashmap[n1+n2] = hashmap.get(n1+n2, 0) + 1
count = 0
for n3 in nums3:
for n4 in nums4:
key = - n3 - n4
if key in hashmap:
count += hashmap[key]
return count
- 手动检查键是否存在
"""
哈希表——类似1.两数之和的拓展
时间复杂度:O(n^2)
"""
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hashmap = dict()
for n1 in nums1:
for n2 in nums2:
#手动检查键是否存在
if n1 + n2 in hashmap:
hashmap[n1+n2] += 1
else:
hashmap[n1+n2] = 1
count = 0
for n3 in nums3:
for n4 in nums4:
key = - n3 - n4
if key in hashmap:
count += hashmap[key]
return count
3、代码问题
defaultdict(lambda: 0)
是一个特殊的字典,它在访问不存在的键时会自动创建该键并使用指定的默认值。这使得在处理需要默认值的场景时,代码更加简洁和方便。
二、力扣383.赎金信【easy】
题目链接:力扣383.赎金信
- 给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)
文档链接:代码随想录
1、思路
- 具体做法
- 遍历
ransomNote
中每个字母,用长度为26的数组ran_count
记录ransomNote
中26字母出现的次数 - 再遍历
magzine
中每个字母,用长度为26的数组mag_count
记录记录magzine
中26字母出现的次数 - 再一一核对是否
mag
的次数都比ran
中的次数来得大
- 遍历
- 时间复杂度: O ( m + n ) O(m+n) O(m+n)
2、代码
- 数组
"""
哈希法——数组
时间复杂度:O(m+n)
"""
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ran_count = [0] * 26 #初始化长度为 26 的列表,分别用于存储赎金信和杂志中每个字母出现的次数
mag_count = [0] * 26
for i in ransomNote:
ran_count[ord(i) - ord('a')] += 1
for i in magazine:
mag_count[ord(i)- ord('a')] += 1
# 使用 all 函数和生成器表达式,判断赎金信中每个字母的出现次数是否都不超过杂志中对应字母的出现次数
# 如果对于所有字母,赎金信中的出现次数都小于等于杂志中的出现次数,则返回 True,否则返回 False
return all (ran_count[i] <= mag_count[i] for i in range(26))
3、代码问题
all
函数- 是 Python 的内置函数,用于检查一个可迭代对象(如列表、元组、生成器等)中的所有元素是否都为 True。
- 如果所有元素都为 True,则返回 True;否则返回 False。
- 生成器表达式
- 生成器表达式是 Python 中一种简洁的语法,用于创建生成器对象。
- 生成器是一种惰性计算的迭代器,它不会一次性计算所有值,而是按需生成值,节省内存。
- 生成器表达式的语法类似于列表推导式,但使用圆括号 () 而不是方括号 [ ]。
三、力扣15.三数之和【medium】
题目链接:
视频链接:
1、思路
167.两数之和Ⅱ——输入有序数组:
- 具体算法:
left
指针从左端开始,right
指针从右端开始- 当两指针的和
sum = target
,退出循环,返还指标数组 - 当两指针的和
sum > target
,移动` - 当两指针的和
sum < target
15.三数之和:
- 这里是要找出所有符合的可能,并且返还的是值,不是下标,所以我们可以先排序,变成非递减有序数组,此时便可以采用相向双指针。
- 第一层
for
循环遍历,左指针选择i
的顺位i+1
,右指针还是最右端开始,形成3个一组,处理和上题一致 - 关键是不能有重复的组合,而且这边是找出所有的可能,刚刚是只要有1个答案就可以
nums[ i ] == nums[ i - 1]
nums[ j ] == nums[ j - 1]
nums[ k ]== nums[ k + 1]
- 第一层
- 时间复杂度:
O
(
n
2
)
O(n^2)
O(n2)
- 排序
sort
: O ( n l o g n ) O(nlogn) O(nlogn) - 外层循环
for
: O ( n − 2 ) O(n-2) O(n−2) - 内层双指针
while
: O ( n ) O(n) O(n) - 在这种情况下,三元组查找的时间复杂度占主导地位,因此整个算法的时间复杂度是 O ( n 2 ) O(n^2) O(n2)
- 排序
2、代码
- 两数之和Ⅱ——输入有序数组
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left = 0
right = len(numbers) -1
while left < right:
s = numbers[left] + numbers[right]
if s == target:
break
if s > target:
right -= 1
else:
left += 1
return [left+1 ,right+1]
#在找到第一个满足条件的两个数后就会停止搜索并输出结果,而不会继续查找其他可能的组合。
- 15.三数之和
"""
相向双指针——适用有序
时间复杂度:O(n^2)
"""
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ans = []
n = len(nums)
for i in range(n-2):
x = nums[i]
#x是和前一个数比较,避免重合
if i > 0 and x == nums[i-1]:
continue
#前三个最小的数已经>0,不可能后面出现加起来有0的情况,直接退出循环体
if x + nums[i+1] + nums[i+2] > 0:
break
#第一个+后两个最大的比0小,说明这个i没有符合条件的组合了,进行下一次迭代
if x + nums[-1] + nums[-2] < 0:
continue
j = i+1
k = n-1
while j < k:
s = x + nums[j] + nums[k]
if s > 0 :
k -= 1
elif s < 0:
j += 1
else:
ans.append([x,nums[j],nums[k]])
j += 1
while j < k and nums[j] == nums[j-1]: #跳过重复
j += 1
k -= 1
while k > j and nums[k] == nums[k+1]: #跳过重复
k -= 1
return ans
3、代码问题
- 避免重复!细节很很重要
break
和continue
的区别
break | continue |
---|---|
用于完全终止循环 | 用于跳过当前循环的剩余部分,直接进入下一次迭代。 |
循环会立即结束,程序的执行流程会跳到循环体之外的下一条语句 | 当前循环的剩余代码将被跳过,循环会继续执行下一次迭代。 |
通常用于在满足某个条件时提前退出循环,避免继续执行不必要的迭代。 | 通常用于在满足某个条件时跳过当前迭代,但不终止整个循环 |
四、力扣18. 四数之和【medium】
题目链接:力扣18. 四数之和
视频链接:代码随想录
1、思路
- 与三数之和一致,这里拓展成枚举2次
- 避免重复的套路一致
target
不再是0- 时间复杂度: O ( n 3 ) O(n^3) O(n3)
2、代码
"""
三数之和的升级版——两次枚举+相向指针法搞定
时间复杂度:O(n^3)
"""
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
ans = []
n = len(nums)
for a in range(n-3):
x = nums[a]
if a > 0 and x == nums[a-1]:
continue
if x + nums[a+1] + nums[a+2] + nums[a+3] > target:
break
if x + nums[-1] + nums[-2] + nums[-3] < target:
continue
for b in range(a+1,n-2):
y = nums[b]
if b > a+1 and y == nums[b-1]:
continue
if x + y + nums[b+1] + nums[b+2] > target:
break
if x + y + nums[-1] + nums[-2] < target:
continue
c = b + 1
d = n - 1
while c < d:
s = x + y + nums[c] + nums[d]
if s > target:
d -= 1
elif s < target:
c += 1
else:
ans.append([ x , y , nums[c] , nums[d] ])
c += 1
while c < d and nums[c] == nums[c-1]:
c += 1
d -= 1
while d >c and nums[d] == nums[d+1]:
d -= 1
return ans
3、代码问题
- 先手撕了一遍,在力扣上编写还是有2个细节上的问题,还是要小心啊!