LeetCode刷题day7——哈希表part2

学习时间

2024.6.12——21:30

哈希表part2

454.四数相加II

题目链接/文章讲解/视频讲解:

建议:本题是 使用map 巧妙解决的问题,好好体会一下 哈希法 如何提高程序执行效率,降低时间复杂度,当然使用哈希法 会提高空间复杂度,但一般来说我们都是舍空间 换时间, 工业开发也是这样。

  1. 思路:根据使用map建议,我想的是:两个数组为一组,记录他们每个元素的和,以及和出现的次数,然后在第二组里 用第一组的map查找是否有相反数,但是卡在了不知道怎么处理索引不同元素相同的情况,所以就AC了2个测试用例。(PS:看到卡哥思路我高兴坏了哈哈哈 没想到自己整体思路几乎和讲解一模一样)
class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3,
                     vector<int>& nums4) {
        unordered_map<int, int> map1, map2, map3, map4;
        int res_count = 0; // 记录有多少个元组
        int map1Count = 0; int map2Count = 0; //记录两组的和的个数
        for (int i = 0; i < nums1.size(); i++) {
            for (int j = 0; j < nums2.size(); j++) {
                map1.insert(pair<int, int>(nums1[i]+nums2[j], map1Count++));
                cout<<map1Count<<endl;
            }
        }
        for (int i = 0; i < nums3.size(); i++) {
            for (int j = 0; j < nums4.size(); j++) {
                if(map1.find(-(nums3[i]+nums4[j]))!=map1.end()){
                    res_count++;//error!!!!
                }
                map2.insert(pair<int, int>(nums3[i]+nums4[j], map2Count++));
                cout<<map2Count<<endl;
            }
        }
        return res_count;
        
    }
};
  1. 根据卡哥讲解:
    (1)首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。
    (2)遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中。
    (3)定义int变量count,用来统计 a+b+c+d = 0 出现的次数。
    (4)在遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。
    (5)最后返回统计值 count 就可以了

发现自己的问题:就是首先是统计和出现的次数,而不是统计总共有多少和!其次就是res_count不能简单的++!

class Solution {
public:
    int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3,
                     vector<int>& nums4) {
        unordered_map<int, int> map1;
        int res_count = 0; // 记录有多少个元组
        for (int a:nums1) {
            for (int b:nums2) {
                map1[a+b]++;
            }
        }
        for (int c:nums3) {
            for (int d:nums4) {
                if(map1.find(-(c+d))!=map1.end()){
                    res_count+=map1[-(c+d)];
                }
            }
        }
        return res_count;
        
    }
};

383.赎金信

题目链接/文章讲解:
建议:本题 和 哈希表part1中的242.有效的字母异位词 是一个思路 ,算是拓展题

  1. 思路:和242类似,用数组做映射,只不过A-Z的ASCII码是65-90,a-z的97-122,数组可以设置的大一点
    (1)先遍历A字符数组,对应字符索引处元素++
    (2)遍历B字符数组,对应字符索引处元素–
    (3)如果小于0,说明B字符有A字符无,立即返回false,反之则是子集
// 类似有效的字母异位词
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int set[100]; // int即可,不是string数组
        // 不需要判断长度,因为有可能是子集

        for (auto a : magazine) {
            set[a - 'A']++;
        }
        for (auto b : ransomNote) {
            set[b - 'A']--;
        }
        for (auto c : set) {
            if (c < 0) {
                return false;
            }
        }

        return true;
    }
};

385.三数之和

题目链接/文章讲解/视频讲解:

建议:本题虽然和 两数之和 很像,也能用哈希法,但用哈希法会很麻烦,双指针法才是正解。

  1. 思路:暴力循环求解,但是不知道怎么去重
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int up = 0;
        int down = 0;
        vector<vector<int>> res;
        for (int i = 0; i < nums.size(); i++) {
            for (int j = i+1; j < nums.size(); j++) {
                for (int k = j+1; k < nums.size(); k++) {
                    if ((nums[i] + nums[j] + nums[k]) == 0 && i != j &&
                        i != k && j != k) {
                        res.push_back( vector<int>{nums[i],nums[j],nums[k]} );
                    }
                }
            }
        }
        return res;
    }
};
  1. 看完卡哥思路:
    (1)首先将数组排序,然后有一层for循环,i从下标0的地方开始,同时定一个下标left 定义在i+1的位置上,定义下标right 在数组结尾的位置上。
    (2)依然还是在数组中找到 abc 使得a + b +c =0,我们这里相当于 a = nums[i],b = nums[left],c = nums[right]。
    (3)移动left 和right, 如果nums[i] + nums[left] + nums[right] > 0 就说明 此时三数之和大了,因为数组是排序后了,所以right下标就应该向左移动,这样才能让三数之和小一些。
    (4)如果 nums[i] + nums[left] + nums[right] < 0 说明 此时 三数之和小了,left 就向右移动,才能让三数之和大一些,直到left与right相遇为止。

但要注意细节问题:a.如果排序后的第一个数>=0,那么绝对不可能;b.去重细节问题:
b.(1) 如果排序后第一次去重采用

if (nums[i] == nums[i + 1]) {
                continue;
            }

错误去重过程

b.(2)如果排序后,找到一个三元组前,则会忽略[0,0,0]情况

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        // 找出a + b + c = 0
        // a = nums[i], b = nums[left], c = nums[right]
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] > 0) { // 有可能都是0,所以不能=0
                return res;
            }

            // 错误去重a方法,将会漏掉-1,-1,2 这种情况
            // if (nums[i] == nums[i + 1]) {
            //     continue;
            // }
            // 正确去重a方法
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1;
            int right = nums.size() - 1;
            // 去重复逻辑如果放在找到三元组之前
            // 则会忽略0,0,0 的情况,可能直接导致 right<=left 了,从而漏掉了
            // 0,0,0 这种三元组
            /*
            while (right > left && nums[right] == nums[right - 1]) right--;
            while (right > left && nums[left] == nums[left + 1]) left++;
            */
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0) {
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    res.push_back(
                        vector<int>{nums[i], nums[left], nums[right]});
                    // 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
                    while (right > left && nums[right] == nums[right - 1])
                        right--;
                    while (right > left && nums[left] == nums[left + 1])
                        left++;
                    // 找到答案时,双指针同时收缩
                    right--;
                    left++;
                }
            }
        }
        return res;
    }
};

收获:两数之和 就不能使用双指针法,因为1.两数之和 要求返回的是索引下标, 而双指针法一定要排序,一旦排序之后原数组的索引就被改变了。如果 两数之和 要求返回的是数值的话,就可以使用双指针法了。

18.四数之和

题目链接/文章讲解/视频讲解:
建议: 要比较一下,本题和 454.四数相加II 的区别,为什么 454.四数相加II 会简单很多,这个想明白了,对本题理解就深刻了。 本题 思路整体和 三数之和一样的,都是双指针,但写的时候 有很多小细节,需要注意。

  1. 初始思路:将1指针作为起始,4指针作为终止,然后23指针一起运动分析,代码如下:
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());

        for (int first = 0; first < nums.size(); first++) {
            if (first > target) {
                break; 
            }

            for (int second = first + 1; second < nums.size(); second++) {
                int third = second + 1;
                int forth = nums.size() - 1;
                if (nums[second] == nums[second - 1] &&
                    nums[third] == nums[third - 1]) {
                    continue;
                }

                while (third < forth) {
                    int sum = nums[first] + nums[second] + nums[third] + nums[forth];
                    if (sum > target)
                        forth--;
                    else if (sum < target)
                        third++;
                    else {
                        res.push_back(vector<int>{nums[first], nums[second],
                                                  nums[third], nums[forth]});
                        //去重
                        while(third<forth && nums[forth] == nums[forth-1]) forth--;
                        while(third<forth && nums[third] == nums[third+1]) third++;
                        while(second<third && nums[second] == nums[second+1]) second++;
                        second++;third++;forth--;
                    }
                }
            }
        }

        return res;
    }
};

…可以看出很垃圾,,剪枝和去重很多条件都没考虑到位,经过看卡哥的代码,然后一点点对应修改现在的缺陷,并通过打印日志来看自己哪里有问题,最终AC

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());

        for (int first = 0; first < nums.size(); first++) {
            if (nums[first] > target && nums[first] >= 0) {
                break;
            }
            // 未去重 加上对nums[first]去重
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            for (int second = first + 1; second < nums.size(); second++) {

                int third = second + 1;
                int forth = nums.size() - 1;
                if (third >= nums.size()) {
                    break;
                }

                // cout<< "一级剪枝+去重:" <<nums[first]<<' '<<nums[second]<<' '<<nums[third]<<' '<<nums[forth]<<endl;
                //  未剪枝 加上二级剪枝
                if ((long long)nums[first] + nums[second] + nums[third] >
                        target &&
                    nums[third] >= 0) {
                    break;
                }
                // cout<< "二级剪枝:" <<nums[first]<<' '<<nums[second]<<' '<<nums[third]<<' '<<nums[forth]<<endl;
                //  去重:因为第一次要运行,应该是对第一次运行之后的判断
                if (second > first + 1 && nums[second] == nums[second - 1] &&
                    nums[third] == nums[third - 1]) {
                    continue;
                }
                // cout<< "二级去重:" <<nums[first]<<' '<<nums[second]<<' '<<nums[third]<<' '<<nums[forth]<<endl;
                while (third < forth) {
                    long long sum = (long long)nums[first] + nums[second] +
                                    nums[third] + nums[forth];
                    if (sum > target)
                        forth--;
                    else if (sum < target)
                        third++;
                    else {
                        // cout<< "找到:" <<nums[first]<<' '<<nums[second]<<' '<<nums[third]<<' '<<nums[forth]<<endl;
                        res.push_back(vector<int>{nums[first], nums[second],
                                                  nums[third], nums[forth]});
                        // 去重
                        while (third < forth && nums[forth] == nums[forth - 1])
                            forth--;
                        while(third<forth && nums[third] == nums[third+1]) third++;
                        while(second<third && nums[second] == nums[second+1]) second++;

                        // cout<<"去重:" <<nums[first]<<' '<<nums[second]<<' '<<nums[third]<<' '<<nums[forth]<<endl; second++;
                        // //这个不能收缩,不然相当于second+了2次
                        third++;
                        forth--;
                    }
                }
            }
        }

        return res;
    }
};
  1. 根据卡哥思路修改代码以及自己的想法

想法1:如果在剪枝处没有判nums>=0中的=0条件,那么下面的测试用例不通过,

nums=[0,0,0,1000000000,1000000000,1000000000,1000000000]
target=1000000000
报错:Line 29: Char 73: runtime error: signed integer overflow: 2000000000 + 1000000000 cannot be represented in type ‘value_type’ (aka ‘int’) (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior solution.cpp:29:73

所以修改sum为long long,并且计算 sum 时,将每个 nums 元素显式转换为 long long 类型。
但是我还是不太懂为什么‘判断=0’加上,sum是long就可以直接通过?我推导了一下运行过程,这个测试用例也没有用到=0的剪枝问题,为什么‘判断=0’不加,sum是long就不可以通过呢?

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        for (int first = 0; first < nums.size(); first++) {
            // 一级剪枝
            if (nums[first] > target && nums[first] >= 0) {//此时有没有=0条件都可AC
                break; // 这里使用break,统一通过最后的return返回
            }
            // 对nums[first]去重 因为相等的话相当于上一次运行的子集,无需重复计算
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            for (int second = first + 1; second < nums.size(); second++) {

                // 二级剪枝
                if (nums[first] + nums[second] > target && nums[second] >= 0) {//此时有没有=0条件都可AC
                    break;
                }
                // 对nums[second]去重
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                int third = second + 1;
                int forth = nums.size() - 1;
                while (third < forth) {
                    // 定义为long型,不然会溢出
                    long long sum = (long long)nums[first] + nums[second] + nums[third] + nums[forth];
                    if (sum> target)
                        forth--;
                    else if (sum < target)
                        third++;
                    else {
                        res.push_back(vector<int>{nums[first], nums[second],
                                                  nums[third], nums[forth]});
                        // 对nums[third]和nums[forth]去重
                        while (third < forth && nums[forth] == nums[forth - 1])
                            forth--;
                        while (third < forth && nums[third] == nums[third + 1])
                            third++;
                        forth--; //一定记得找到以后要收缩双指针!
                        third++;
                    }
                }
            }
        }

        return res;
    }
};

  • 36
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值