算法训练营第五天 | 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
相关推荐
geovindu34 分钟前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人3 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康4 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长4 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David5 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
xckkcxxck7 小时前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T8 小时前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊8 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo
AAA修煤气灶刘哥10 小时前
我都切到下一张图了,Agent 怎么还在解释上一张?
人工智能·算法·架构
Navigator_Z10 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode