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

Leetcode454.四数相加II

题目链接:454. 四数相加 II

C++:

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
        unordered_map<int, int> map;
        for(int a: nums1)
        {
            for(int b: nums2)
            {
                map[a+b]++;
            }
        }
        int count = 0;
        for(int c: nums3)
        {
            for(int d: nums4)
            {
                int target = -(c + d);
                if(map.find(target) != map.end())
                    count += map[target];
            }
        }
        return count;
    }
};

Python:

lambda函数:

   (1)用法:lambda 参数列表 : 表达式

   (2)lambda函数是匿名的,但是有自己的输入输出和名称空间

   (3)举例:lambda x, y : x + y :输入为x值和y值,输出为它们的和x+y的值

   (4)和defaultdict结合使用:r = defaultdict(lambda : 0),输出的字典r的所有value值都为0

python数据类型——字典dict:

   (1)定义:字典元素以键值对存在:key(键):value(值),d = {}

   (2)d[key] = d.get(key,0)+1:d[key]表示键为key的值value,找不到则报错;d.get(key,0)表示找到键为key的值,找不到则赋值为0

from collections import defaultdict
class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        map = defaultdict(lambda: 0)
        count = 0
        for a in nums1:
            for b in nums2:
                map[a+b] += 1
        for c in nums3:
            for d in nums4:
                count += map.get(-(c+d), 0)
        return count

Leetcode383. 赎金信

题目链接:383. 赎金信

C++:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        vector<int> hash(26, 0);
        for(auto i: ransomNote)
        {
            hash[i - 'a']++;
        }
        for(auto j: magazine)
        {
            hash[j - 'a']--;
        }
        for(int a : hash)
        {
            if(a > 0)
                return false;
        }
        return true;
    }
};

Python:

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        hashmap = {}
        for i in magazine:
            hashmap[i] = hashmap.get(i, 0) + 1
        for j in ransomNote:
            if hashmap.get(j, 0) == 0:
                return False
            hashmap[j] -= 1
        return True

Leetcode15. 三数之和 

题目链接:15. 三数之和

C++:

使用sort对数组进行排序需要包含头文件#include<algorithm>:

        (1)对数组升序排序:sort(nums.begin(), nums.end());

        (2)对数组降序排序:sort(nums.begin(), nums.end(), greater<int>());

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> result;
        for(int i=0; i < nums.size(); i++)
        {
            if(nums[i] > 0)
                return result;
            //去重i
            if(i > 0 && nums[i] == nums[i-1])
                continue;
            int left = i+1;
            int right = nums.size()-1;
            while(left < right)
            {
                if(nums[i] + nums[left] + nums[right] < 0)
                {
                    left++;
                }
                else if(nums[i] + nums[left] + nums[right] > 0)
                {
                    right--;
                }
                else
                {
                    result.push_back(vector<int>{nums[i], nums[left], nums[right]});
                    while(left < right && nums[left] == nums[left+1])
                        left++;
                    while(left < right && nums[right] == nums[right-1])
                        right--;
                    left++;
                    right--;
                }
            }
        }
        return result;
    }
};

Python:

排序:

   (1)python升序排序,列表本身修改:

                nums.sort()

   (2)python升序排序,返回新列表:

                sorted(nums)

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        result = []
        nums.sort()
        for i in range(len(nums)):
            if nums[i] > 0:
                return result
            if i > 0 and nums[i] == nums[i-1]:
                continue
            left = i + 1
            right = len(nums) - 1
            while left < right:
                if nums[i] + nums[left] + nums[right] < 0:
                    left += 1
                elif nums[i] + nums[left] + nums[right] > 0:
                    right -= 1
                else:
                    result.append([nums[i], 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
        return result

Leetcode18. 四数之和 

题目链接:18. 四数之和

C++:

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> results;
        for(int i = 0; i < nums.size(); i++)
        {
            if(target >= 0 && nums[i] > target)
                break;
            if(i > 0 && nums[i] == nums[i-1])
                continue;
            for(int j = i+1; j < nums.size(); j++)
            {
                if(target >= 0 && nums[i] + nums[j] > target)
                    break;
                if(j > i+1 && nums[j] == nums[j-1])
                    continue;
                int left = j+1;
                int right = nums.size() - 1;
                while(left < right)
                {
                    //强制类型转换
                    if((long)nums[i] + nums[j] + nums[left] + nums[right] > target)
                        right--;
                    //强制类型转换
                    else if((long)nums[i] + nums[j] + nums[left] + nums[right] < target)
                        left++;
                    else
                    {
                        results.push_back(vector<int> {nums[i], nums[j], nums[left], nums[right]});
                        while(left < right && nums[left] == nums[left+1])
                            left++;
                        while(left < right && nums[right] == nums[right-1])
                            right--;
                        left++;
                        right--;
                    }
                }
            }
        }
        return results;
    }
};

Python:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        result = []
        nums.sort()
        for k in range(len(nums)):
            if nums[k] > target and target > 0:
                break
            if k > 0 and nums[k] == nums[k-1]:
                continue
            for i in range(k+1, len(nums)):
                if nums[k] + nums[i] > target and target > 0:
                    break
                if i > k+1 and nums[i] == nums[i-1]:
                    continue
                left = i + 1
                right = len(nums) - 1
                while left < right:
                    if nums[k] + nums[i] + nums[left] + nums[right] > target:
                        right -= 1
                    elif nums[k] + nums[i] + nums[left] + nums[right] < target:
                        left += 1
                    else:
                        result.append([nums[k], nums[i], 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
        return result
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码随想录算法训练营是一个优质的学习和讨论平台,提供了丰富的算法训练内容和讨论交流机会。在训练营中,学员们可以通过观看视频讲解来学习算法知识,并根据讲解内容进行刷题练习。此外,训练营还提供了刷题建议,例如先看视频、了解自己所使用的编程语言、使用日志等方法来提高刷题效果和语言掌握程度。 训练营中的讨论内容非常丰富,涵盖了各种算法知识点和解题方法。例如,在第14天的训练营中,讲解了二叉树的理论基础、递归遍历、迭代遍历和统一遍历的内容。此外,在讨论中还分享了相关的博客文章和配图,帮助学员更好地理解和掌握二叉树的遍历方法。 训练营还提供了每日的讨论知识点,例如在第15天的讨论中,介绍了层序遍历的方法和使用队列来模拟一层一层遍历的效果。在第16天的讨论中,重点讨论了如何进行调试(debug)的方法,认为掌握调试技巧可以帮助学员更好地解决问题和写出正确的算法代码。 总之,代码随想录算法训练营是一个提供优质学习和讨论环境的平台,可以帮助学员系统地学习算法知识,并提供了丰富的讨论内容和刷题建议来提高算法编程能力。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [代码随想录算法训练营每日精华](https://blog.csdn.net/weixin_38556197/article/details/128462133)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值