重启人生1.0-day7:454.四数相加II ;383. 赎金信 ; 15. 三数之和

454.四数相加II

   def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        dict_SumAB = {}
        for i in nums1:
            for j in nums2:
                sumAB = i + j
                if sumAB in dict_SumAB:
                    dict_SumAB[sumAB] += 1
                else:
                    dict_SumAB[sumAB] = 1
        count = 0
        for m in nums3:
            for n in nums4:
                target = 0 - (m + n)
                if target in dict_SumAB:
                    count += dict_SumAB[target]
        return count
  1. 赎金信
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        nums = [0] * 26
        for i in magazine:
            nums[ord(i) - ord("a")] += 1
        for i in ransomNote:
            nums[ord(i) - ord("a")] -= 1
        for x in nums:
            if x < 0:
                return False
        return True
  1. 三数之和
        nums.sort()
        n = len(nums)
        result = []

        for i in range(n):

            # 初步筛查,排序后的数组,如果某个值开始大于0,则后面的数就不用再判断了
            if nums[i] > 0:
                return result

            # i去重
            if i > 0 and nums[i] == nums[i - 1]:
                continue

            # 双指针
            left = i + 1
            right = n - 1

            while right > left:
                sum_ = nums[i] + nums[left] + nums[right]
                if sum_ > 0:
                    right -= 1
                elif sum_ < 0:
                    left += 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
                    right -= 1
                    left += 1
        return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值