代码随想录算法训练营第七天 | 454.四数相加II | 383. 赎金信 | 15. 三数之和 | 18. 四数之和

文章介绍了在解决编程题目中,15题三数之和和18题四数之和的解决方案,强调了使用双指针(实际上在18题中是三指针)以及去重的重要性。通过实例展示了如何利用字典、Counter和数组数据结构来处理这些问题。
摘要由CSDN通过智能技术生成

15和18题其实不是哈希表,是双指针,要考虑去重的细节。

454题 四数相加2

思路:四个数组,两两一组,把a+b的值和个数存入字典(即哈希表),即 counter[sum] =counter.get(sum, 0) + 1。如果 -(c+d)的值=a+b,则把计数器res += a+b对应的个数。
class Solution(object):
    def fourSumCount(self, nums1, nums2, nums3, nums4):
        counter = dict()
        for i in nums1:
            for j in nums2:
                sum = i + j
                counter[sum] = counter.get(sum, 0) + 1
        res = 0
        for i in nums3:
            for i in nums4:
                sum2 = -i - j
                if sum2 in sum:
                    res += counter[sum2]
        return res

383题 赎金信

方法一:字典
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        counts = dict()
        for i in magazine:
            counts[i] = counts.get(i, 0) + 1
        for c in ransomNote:
            if c not in counts or counts[c] == 0:
                return False
                counts[c] -= 1
        return True

方法二:Counter
只有当counter1中的键值对含在counter2里时,相减会返回{}空字典,即为False,not False为True
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        from collections import Counter
        return not Counter(ransomNote) - Counter(magazine)

方法三:数组
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        ransom_count = [0] * 26
        magazine_count = [0] * 26
        for i in ransomNote:
            ransom_count[ord(i) - ord('a')] += 1
        for j in magazine:
            magazine_count[ord(j) - ord('a')] += 1
        return all(ransom_count[i] <= magazine_count[i] for i in range(26))
return all 即 当all后面所有的例子都成立,返回True,反之。

15题 三数之和

不是哈希表,用双指针(其实是三指针)
难点:去重
注意:while right > left and nums[right] == nums[right - 1]:
     while right > left and nums[left] == nums[left + 1]:
这两句里面的right>left不可省略,不然会出现如[0,0,0]这个案例,right一直向左移,移到第一个0,后面right-=1,就会报错。不是说在大循环里有了的条件,在小循环里就可以省略不写了。
class Solution(object):
    def threeSum(self, nums):
        nums.sort()
        result = []
        for i in range(len(nums)):
            if nums[i] > 0:
                break
            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
                    right -= 1
                    left += 1
        return result

18题 四数之和

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        result = []
        for i in range(n):
            if nums[i] > target and nums[i] > 0 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, right = j+1, 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
                    elif s < target:
                        left += 1
                    else:
                        right -= 1
        return result
  • 19
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值