当前位置:   article > 正文

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

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

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题 四数之和

  1. class Solution:
  2. def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
  3. nums.sort()
  4. n = len(nums)
  5. result = []
  6. for i in range(n):
  7. if nums[i] > target and nums[i] > 0 and target > 0:# 剪枝(可省)
  8. break
  9. if i > 0 and nums[i] == nums[i-1]:# 去重
  10. continue
  11. for j in range(i+1, n):
  12. if nums[i] + nums[j] > target and target > 0: #剪枝(可省)
  13. break
  14. if j > i+1 and nums[j] == nums[j-1]: # 去重
  15. continue
  16. left, right = j+1, n-1
  17. while left < right:
  18. s = nums[i] + nums[j] + nums[left] + nums[right]
  19. if s == target:
  20. result.append([nums[i], nums[j], nums[left], nums[right]])
  21. while left < right and nums[left] == nums[left+1]:
  22. left += 1
  23. while left < right and nums[right] == nums[right-1]:
  24. right -= 1
  25. left += 1
  26. right -= 1
  27. elif s < target:
  28. left += 1
  29. else:
  30. right -= 1
  31. return result
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/943341
推荐阅读
相关标签
  

闽ICP备14008679号