代码随想录算法训练营day7|● 454.四数相加II ● 383. 赎金信 ● 15. 三数之和 ● 18.四数之和
学习资料:https://programmercarl.com/0015.三数之和.html#其他语言版本
学习记录:
454.四数相加(hash_dict,前两个数一组遍历a+b,后两个数一组遍历找0-(a+b))
点击查看代码
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
hash_map = dict()
for i in nums1:
for j in nums2:
key=i+j
hash_map[key]=hash_map.get(key, 0)+1
count = 0
for i in nums3:
for j in nums4:
key=0-(i+j)
if key in hash_map:
count += hash_map[key]
return count
点击查看代码
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ran_list = [0]*26
mag_list = [0]*26
for i in ransomNote:
index= ord(i)-ord('a')
ran_list[index] += 1
for i in magazine:
index = ord(i)-ord('a')
mag_list[index] += 1
for i in range(26):
if ran_list[i]<=mag_list[i]:
pass
else:
return False
return True
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
return result
# 第一次去重
if i > 0 and nums[i] == nums[i-1]:
continue
# 双指针
left = i + 1
right = len(nums)-1
while right > left:
sum = nums[i]+nums[left]+nums[right]
if sum < 0:
left += 1
elif sum > 0:
right -= 1
else:
result.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
left += 1
right -= 1
return result
18.四数之和(此时target不为0,可正可负,在双指针left,right的基础上在前面加上i和j,用双重循环,加上剪枝和去重)
点击查看代码
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
n=len(nums)
result = []
for i in range(n):
# 一级剪枝
if nums[i]>target and target>0:
break
# 一级去重
if i>0 and nums[i] == nums[i-1]:
continue
for j in range(i+1, n):
# 二级剪枝
if nums[i]+nums[j]>target and target > 0:
break
# 二级去重
if j>i+1 and nums[j]==nums[j-1]:
continue
# 开始类似三数之和操作
left = j+1
right = n-1
while left<right:
s = nums[i]+nums[j]+nums[left]+nums[right]
if s==target:
result.append([nums[i], nums[j], nums[left], nums[right]])
# 在收获了一个结果后开始去重
while left<right and nums[left]==nums[left+1]:
left += 1
while left<right and nums[right]==nums[right-1]:
right -= 1
left += 1
right -= 1
if s>target:
right -= 1
if s<target:
left += 1
return result
PS:18题明天再做吧,假期结束啦,今天吃土豆烧排骨、甜椒炒肉、糖醋莲白,幸福~~~
2024.10.7 补上18了,好难!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?