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

今日任务

●  454.四数相加II

●  383. 赎金信

●  15. 三数之和

●  18. 四数之和

详细布置

454.四数相加II

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

题目链接:. - 力扣(LeetCode)

题目链接/文章讲解/视频讲解:代码随想录

暴力解:

四层循环遍历,每找到一种就累计一次(缺陷是最后一次的数组每次都需要遍历一遍)


    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int res = 0;
        for(int i=0;i<nums1.length;i++){
            for(int j=0;j<nums2.length;j++){
                for(int k=0;k<nums3.length;k++){
                    for(int l=0;l<nums4.length;l++){
                        if(nums1[i]+nums2[j]+nums3[k]+nums4[l] == 0){
                            res++;
                        }
                    }
                }
            }
        }
        return res;
    }
优化:

利用分治,分别两两数组计算,变成两数之和的问题

// 优化思路: 分治处理,再利用map累计次数
    //
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int res = 0;
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        //汇总前两个数组,并用map记录累加和及相同累加和出现的次数
        for(int i:nums1){
            for(int j:nums2){
                int sum = i+j;
                map.put(sum,map.getOrDefault(sum,0)+1);
            }
        }
        for(int i:nums3){
            for(int j:nums4){
                int sum = i+j;
                if(map.containsKey(-sum)){
                    res += map.get(-sum);
                }
            }
        }
        return res;
    }
       

383. 赎金信

建议:本题 和 242.有效的字母异位词 是一个思路 ,算是拓展题

题目链接:. - 力扣(LeetCode)

题目链接/文章讲解:代码随想录

ransomNote 和 magazine 由小写英文字母组成 -- 第一反应就是,可以用 s.charAt(i)-'a' 的方式 用 26 个数组来做为字典表

//ransomNote 和 magazine 由小写英文字母组成 -- 说明可以用 s.charAt(i)-'a' 的方式来记录对应的元素
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] dirt = new int[26];
        for(int i=0;i<magazine.length();i++){
            dirt[magazine.charAt(i)-'a'] ++;
        }
        boolean res = true;
        for(int i=0;i<ransomNote.length();i++){
            if(dirt[ransomNote.charAt(i)-'a']-- ==0){
                res = false;
                break;
            }
        }
        return res;
    }

15. 三数之和

建议:本题虽然和 两数之和 很像,也能用哈希法,但用哈希法会很麻烦,双指针法才是正解,可以先看视频理解一下 双指针法的思路,文章中讲解的,没问题 哈希法很麻烦。

题目链接:. - 力扣(LeetCode)

题目链接/文章讲解/视频讲解:代码随想录

哈希解:

public List<List<Integer>> threeSum(int[] nums) {
        Map<String,List<Integer>> res = new HashMap<>();
        //key 累加和,val: 组成的元素的索引组合
        Map<Integer,List<List<Integer>>> map = new HashMap<>();
        int l=0;
        int r=1;
        while(l<r && l < nums.length -1 && r < nums.length){
            int sum = nums[l] + nums[r];
            List<List<Integer>> val = map.get(sum);
            if(val == null){
                val = new ArrayList();
            }
            List<Integer> son = new ArrayList(2);
            son.add(l);
            son.add(r++);
            val.add(son);
            map.put(sum,val); 

            //每次右指针到头时,都需要重置左右指针
            if(r == nums.length ){
                l++;
                r = l+1;
            }
        }
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(-nums[i])){
                List<List<Integer>> val = map.get(-nums[i]);
                for(List<Integer> list:val){
                    if(!list.contains(i)){
                        List<Integer> sonList = new ArrayList();
                        sonList.add(nums[list.get(0)]);
                        sonList.add(nums[list.get(1)]);
                        sonList.add(nums[i]);
                    
                        String key = sonList.stream().sorted().map(Object::toString).collect(Collectors.joining());
                        res.put(key,sonList);
                    }
                }
            }
        }

        return new ArrayList<>(res.values());
    }

三指针解:

 /**
     * [-1,0,1,2,-1,-4]
     * 排序
     * [-4,-1,-1,0,1,2]
     *   p  l        r --> nums[l] + nums[r] < 0-(-4) ,即说明当前双指针对应元素的值偏小,又因为数组已经升序排序了,这个时候逐步右移l,
     *   p         l r --> 一直右移到最右侧,说明当前定点值太小,逐步右移定点P,再执行上述的操作过程
     *      p  l     r --> nums[l] + nums[r] = 0-(-1) ,满足条件,再逐步右移定点P,再执行上述的操作过程
     *        p  l   r --> nums[l] + nums[r] > 0-(-1) ,即说明当前双指针对应元素的值偏大,又因为数组已经升序排序了,这个时候逐步左移r
     *        p  l r   --> 当移动到 l + 1 位置时,nums[l] + nums[r] = 0-(-1),满足条件,再逐步右移定点P,再执行上述的操作过程
     *           p l r --> 当p点已经移动到了倒数第三位的时候,只需要计算最后三位的和即可(这里还有一个隐形条件,如果,定点已经到正数了则最右侧的值不管怎么加都是大于0的,这个时候直接跳出循环即可)
     * 输出:
     * [-1,-1,2]
     * [-1,0,1]
     *
     * 核心思路:
     *    1.对数组进行排序,从最左侧定点之后,再通过双指针的方式依次遍历定点+1 与 len -1 对应位置的值
     * @param nums
     * @return
     */
    public static List<List<Integer>> threeSum(int[] nums) {
        if(nums.length<3){
            return null;
        }
        //优先数组排序
        Arrays.sort(nums);
        if(nums[0] > 0){
            return null;
        }

        List<List<Integer>> ans = new ArrayList<>();
        int p = 0;
        //指定定点边界
        while(p < nums.length-1 && nums[p] <= 0){
            int target = 0-nums[p];
            //左指针
            int l = p+1;
            //右指针
            int r = nums.length -1;
            while(l<r){
                int c = nums[l] + nums[r];
                if(c < target){
                    //即说明当前双指针对应元素的值偏小,又因为数组已经升序排序了,这个时候逐步右移l
                    l++;
                }else if(c > target){
                    //即说明当前双指针对应元素的值偏大,又因为数组已经升序排序了,这个时候逐步左移r
                    r--;
                }else{
                    //避免重复:如果l+1位置的值与l位置的一致,则继续右移才行
                    while (l<r && nums[l]==nums[l+1]){ l++;}
                    //避免重复:如果r-1位置的值与r位置的一致,则继续左移才行
                    while (l<r && nums[r]==nums[r-1]){ r++;}
                    //相等:则满足条件,添加元素
                    List<Integer> list =  new ArrayList<>(3);
                    list.add(nums[p]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    ans.add(list);
                    break;
                }
            }
            //右移定点
            p++;
        }
        return ans;
    }

18. 四数之和

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

题目链接:

题目链接/文章讲解/视频讲解:代码随想录

暴力四指针求解

public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();

        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue; // 去重

            for (int j = i + 1; j < nums.length; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue; // 去重

                int l = j + 1;
                int r = nums.length - 1;

                while (l < r) {
                    if (r < nums.length - 1 && nums[r] == nums[r + 1]) { // 去重
                        r--;
                    } else if (l > j + 1 && nums[l] == nums[l - 1]) { // 去重
                        l++;
                    } else if ((long) nums[i] + nums[j] + nums[l] + nums[r] > target) { 
                        r--;
                    } else if ((long) nums[i] + nums[j] + nums[l] + nums[r] < target) {
                        l++;
                    } else {
                        res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                        l++; r--;
                    }
                }
            }
        }

        return res;
    }

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值