代码随想录算法训练营第6天|454,383,15(重写),18(

2025-08-11  本文已影响0人  攻城狮科学家
  1. 四数相加II
    学到了
    class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
    hashmap = dict()
    for i in nums1:
    for j in nums2:
    if i+j in hashmap:
    hashmap[i+j] += 1
    else:
    hashmap[i+j] = 1

    count = 0
    for n3 in nums3:
    for n4 in nums4:
    key = - n3 - n4
    if key in hashmap:
    count += hashmap[key]
    return count

  2. 赎金信
    class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
    hashmap = defaultdict(int)

    for x in magazine:
    hashmap[x] += 1

    for x in ransomNote:
    value = hashmap.get(x)
    if not value:
    return False
    else:
    hashmap[x] -= 1

    return True

  3. 三数之和
    自己写的话,写了个循环,还是卡在去重上了,需要重点再练一下
    class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
    result = []
    nums.sort()

    for i in range(len(nums)):
        # 如果第一个元素已经大于0,不需要进一步检查
        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
                    
                right -= 1
                left += 1
                
    return result
    
  4. 四数之和
    需要重写
    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

上一篇 下一篇

猜你喜欢

热点阅读