算法训练营第五天 | 454.四数相加II\ 383. 赎金信\15. 三数之和\ 18. 四数之和

454.四数相加II

题目

思路与解法

第一想法:
carl的讲解: 前两个为一组,后两个为一组。遍历前两个可能的加值,再在后两组中寻找有没有前面值的负值,若有就是一组。

我认为,重点在于将问题简化为前两个数组和后两个数组的逻辑。

python 复制代码
class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        from collections import defaultdict
        sum_dict = defaultdict(int)
        for a in nums1:
            for b in nums2:
                sum_dict[a+b] += 1
        count = 0
        for c in nums3:
            for d in nums4:
                if (0-c-d) in sum_dict:
                    count += sum_dict[0-c-d]
        return count 

383. 赎金信

题目

思路与解法

第一想法: 将magazine中的字母存在字典中,key是字母,value是出现的次数。然后遍历ransomNote的字母,在magazine字典中出现一次就value减一,value小于0就返回False。若字典中没有,就直接返会False。最后都通过了,就返回True。

python 复制代码
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        from collections import defaultdict
        magazine_dict = defaultdict(int)
        for a in magazine:
            magazine_dict[a] += 1
        for b in ransomNote:
            if b not in magazine_dict:
                return False
            magazine_dict[b] -= 1
            if magazine_dict[b] < 0:
                return False
            
        return True

15. 三数之和

题目

思路与解法

第一想法: 双指针,三个数,for i in enumerate(nums),i代表第一个,low = i+1, fast = low+1,代表后面两个。然后low 和 fast遍历数组来和i相加看是不是等于0。i也不断往后遍历。

但是忽略了去重。加上去重就是对的,但是超时了。

python 复制代码
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        res = []
        nums.sort()
        for i, num  in enumerate(nums):
            low = i + 1
            if i > 0 and nums[i] == nums[i-1]:
                continue
            while low < len(nums) -1 :
                fast = low + 1
                while fast < len(nums):
                    if nums[low] + nums[fast] + num == 0:
                        res.append([num, nums[low], nums[fast]])
                    while fast + 1 < len(nums) and nums[fast + 1] == nums[fast]:
                        fast += 1
                    fast += 1
                while low + 1 < len(nums) -1 and nums[low+1] == nums[low]:
                    low += 1
                low += 1
        return res
        

carl的讲解: 让fast指针从最右边开始,因为排序了,所以fast(right)指向的是最大值

python 复制代码
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

18. 四数之和

题目

思路与解法

carl的讲解:

python 复制代码
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
相关推荐
2301_764441335 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI5 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly5 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives5 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1236 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao9856 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神7 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜7 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
Proxy_ZZ08 小时前
用Matlab绘制BER曲线对比SPA与Min-Sum性能
人工智能·算法·机器学习
黎阳之光8 小时前
黎阳之光:以视频孪生领跑全球,赋能数字孪生水利智能监测新征程
大数据·人工智能·算法·安全·数字孪生