代码随想录算法训练营|454.四数相加II;383. 赎金信;15. 三数之和;18. 四数之和
454.四数相加II
题目链接: 454.四数相加II
文档讲解: 代码随想录
题目难度:简单
思路:使用哈希表,类型包括哈希数组、集合set和映射map(可以理解为字典),以及了解解决哈希冲突的两种方式:拉链法(链表)和线性探测法(顺序存进下一个空间)。
时间复杂度:O(n)
下面展示 代码
:
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
# 哈希表
hashmap = {}
res = 0
for n1 in nums1:
for n2 in nums2:
if n1 + n2 in hashmap:
hashmap[n1+n2] += 1
else:
hashmap[n1+n2] = 1
# 处理nums3和nums4
for n3 in nums3:
for n4 in nums4:
value = -(n3+n4)
if value in hashmap:
res += hashmap[value]
return res
383. 赎金信
题目链接: 383. 赎金信
文档讲解: 代码随想录
题目难度:简单
思路:哈希数组和字典均可解决此类问题。
代码
如下
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
# 哈希表把magazine中所有字符及出现次数存储下来
hashmap = dict()
for i in magazine:
if i in hashmap:
hashmap[i] += 1
else:
hashmap[i] = 1
# 与ransomNote对比
for i in ransomNote:
if i in hashmap and hashmap[i] > 0:
hashmap[i] -= 1
else:
return False
return True
15. 三数之和
题目链接: 15. 三数之和
文档讲解: 代码随想录
题目难度:中等
思路:1、数组升序排列;2、遍历,左右指针从[i , len(num)-1]开始搜索;3、有效去重和剪枝
时间复杂度:O(n^2)
代码
如下
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# 双指针法
res = []
if nums == None:
return res
else:
# 1、数组升序排列
nums.sort()
# 2、开始遍历
for i in range(len(nums)):
if nums[i] > 0:
# 升序排列,[i. left ,right]如果num[i] > 0, 后面的和必然大于0
return res
# 去重(相同的元素的情况已经处理过了,可直接不处理,不然会造成结果重复)
if i > 0 and nums[i] == nums[i - 1]:
continue
# 在此处定义,因为每次都得从头遍历
left = i + 1
right = len(nums) - 1
while right > left:
sum1 = nums[i] + nums[left] + nums[right]
if sum1 == 0:
# 去重,减少计算量
res.append([nums[i], nums[left], nums[right]])
while right > left and nums[right] == nums[right - 1]:
right -= 1
while right > left and nums[left] == nums[left + 1]:
left += 1
# sum == 0了,必然只有两个指针同时移动时才能有新的满足条件的值
left += 1
right -= 1
elif sum1 < 0:
left += 1
else:
right -= 1
return res
18. 四数之和
题目链接: 18. 四数之和
文档讲解: 代码随想录
题目难度:中等
思路:同三数之和相同,加一个for循环即可
时间复杂度:O(n^3)
代码
如下
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res = []
# 同三数之和相比,多了一层循环,也多了去重和剪枝操作
for i in range(len(nums)):
if nums[i] == nums[i - 1] and i > 0:
continue
for j in range(i+1, len(nums)):
# 剪枝
if nums[i] + nums[j] > target and target > 0:
break
# 去重
if nums[j] == nums[j - 1] and j > i + 1:
continue
left = j + 1
right = len(nums) - 1
while left < right:
value = nums[i] + nums[j] + nums[left] + nums[right]
if value == target:
res.append([nums[i] ,nums[j], nums[left], nums[right]])
# 去重
while right > left and nums[right] == nums[right - 1]:
right -= 1
while right > left and nums[left] == nums[left + 1]:
left += 1
# sum == 0了,必然只有两个指针同时移动时才能有新的满足条件的值
left += 1
right -= 1
elif value < target:
left += 1
else:
right -= 1
return res