代码随想录算法训练营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

383.赎金信(类似于有效的字母异位字,只要note里字母统计个数小于等于magzinine里的统计字母个数,则返回True)
点击查看代码
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
15.三数之和(不用hash表,用左右指针法,重点在于结果去重;初始数组排序;i代表a遍历全数组,left=i+1, right=nums.size-1;left和right向中间靠拢;因为要三个数所以left 点击查看代码
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了,好难!!

posted @   Tristan241001  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示