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

文章详细描述了解决四数之和问题的一种方法,利用哈希表存储两数之和及其出现次数,结合双指针遍历剩余数组寻找满足条件的组合,同时讨论了如何简化代码并扩展到更复杂的版本如数组内寻找四个元素和为0的组合
摘要由CSDN通过智能技术生成

454. 四数相加 II

还是没有想到如何妥当使用map,看题解后自己敲出了代码

class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int sum12 = 0;
        HashMap<Integer, Integer> hm = new HashMap<>();
        // key存两数和 value对应和出现的次数
        for (int n1 : nums1) {
            for (int n2 : nums2) {
                sum12 = n1 + n2;
                if (hm.containsKey(sum12)) {
                    hm.replace(sum12, hm.get(sum12) + 1);
                } else {
                    hm.put(sum12, 1);
                }
            }
        }
        int sum34 = 0;
        int count = 0;
        for (int n3 : nums3) {
            for (int n4 : nums4) {
                sum34 = n3 + n4;
                if (hm.containsKey(-sum34)) {
                    count += hm.get(-sum34);
                }
            }
        }
        return count;
    }
}

本题是使用哈希法的经典题目,而0015.三数之和 (opens new window)0018.四数之和 (opens new window)并不合适使用哈希法,因为三数之和和四数之和这两道题目使用哈希法在不超时的情况下做到对结果去重是很困难的,很有多细节需要处理。

而这道题目是四个独立的数组,只要找到A[i] + B[j] + C[k] + D[l] = 0就可以,不用考虑有重复的四个元素相加等于0的情况,所以相对于题目18. 四数之和,题目15.三数之和,还是简单了不少!

如果本题想难度升级:就是给出一个数组(而不是四个数组),在这里找出四个元素相加等于0,答案中不可以包含重复的四元组,大家可以思考一下,后续可见代码随想录 (programmercarl.com)

383. 赎金信

力扣题目链接

import java.util.HashMap;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        HashMap<Character,Integer> hm = new HashMap<>();
        for(char c : magazine.toCharArray()){
            if(hm.containsKey(c)){
                hm.put(c,hm.get(c)+1);
            }else{
                hm.put(c,1);
            }
        }
        for(char c: ransomNote.toCharArray()){
            if(hm.containsKey(c)){
                if(hm.get(c)>=1){
                    hm.put(c,hm.get(c)-1);
                }else {
                    return false;
                }
            }else{
                return false;
            }
        }
        return true;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

记录一种简便写法

hm.put(key, hm.getOrDefault(key, 0) + 1);
//等价于
if(hm.containsKey(sum)){
    hm.put(sum,hm.get(sum)+1);
}else{
    hm.put(sum,1)
}

15.三数之和 

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。

示例 2:

输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。

示例 3:

输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。

思路

这是一种nSum问题,基本思路是先数组排序,后遍历+双指针 一层一层计算,关键是边界处理,重复处理

具体说 先排序使得左右指针指向一大一下,有了含义,于是当三数和大于0,right--;小于0 left++;等于0则加进结果中,其中由于排序了,连续相同的值就可以去掉,否则会存在重复的三元组。

排序+双指针

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for(int i=0; i<nums.length; i++){
            if(nums[i] > 0){
                return res;
            }
            //a的去重
            if(i>0 && nums[i] == nums[i-1]){
                continue;
            }
            int left = i+1;
            int right = nums.length-1;
            //双指针 找两个 所以不能 =
            while(left < right){
                if(nums[i] + nums[left] + nums[right] > 0){
                    right--;
                }else if(nums[i] + nums[left] + nums[right] < 0){
                    left++;
                }else {
                    //Java初始化一个Arraylist的方法:
                    //List<String> list = Arrays.asList("1", "2", "3");
                    res.add(Arrays.asList(nums[i],nums[left],nums[right]));
                    //b c去重
                    while(right>left && nums[left] == nums[left+1])left++;
                    while(right>left && nums[right] == nums[right-1]) right--;
                    //找到答案 双指针移动
                    left++;
                    right--;
                }

            }
        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

根据这个思路可以引入递归,写出通解

排序+双指针+递归

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        //首先排序 时间复杂度nlogn 避免后续递归过程中无必要的时间损失
        Arrays.sort(nums);
        return getnSum(nums,3,0,0);
    }
    //一定要明确递归函数的定义(返回的是什么)
    //这里递归实际是取代了原有的i迭代,返回当i计算完毕后的结果

    //nSum的通用解法
    //n填写的是想计算的是几数之和,start是从何处开始索引,一般为0,target是求和为多少,本题填0
    public List<List<Integer>> getnSum(int[] nums,int n,int start,int target){
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        //至少是2Sum 且数组大小不应该小于n
        if(n < 2 || len < n){
            return res;
        }
        //当n大于2时的通用情况 递归计算(n-1)Sum问题
        if(n > 2) {
            for(int i = start; i < len ; i++){
                //此时target为原target减去当前遍历的数
                //函数返回的是包含n-1元组的二维列表
                //注意这里start 为 i+1
                List<List<Integer>> sub = getnSum(nums,n - 1,i + 1,target - nums[i]);
                for(List<Integer> arr : sub){
                    arr.add(nums[i]);
                    res.add(arr);
                }
                //边界处理 去重 注意此处比较i的下一项
                while(i < len-1 &&nums[i] == nums[i+1]) i++;
            }
        }
        else if(n == 2){
            //n为2 求两数和问题,双指针
            int left = start;
            int right = len-1;
            while(left < right){
                int sum = nums[left] + nums[right];
                if(sum < target) left++;
                else if(sum > target) right--;
                else{
                    res.add(new ArrayList<>(Arrays.asList(nums[left],nums[right])));
                    while(left < right && nums[left] == nums[left+1]) left++;
                    while(left < right && nums[right] == nums[right-1]) right--;

                    left++;
                    right--;
                }
            }

            // 双指针那一套操作
//            int lo = start, hi = len - 1;
//            while (lo < hi) {
//                int sum = nums[lo] + nums[hi];
//                int left = nums[lo], right = nums[hi];
//                if (sum < target) {
//                    while (lo < hi && nums[lo] == left) lo++;
//                } else if (sum > target) {
//                    while (lo < hi && nums[hi] == right) hi--;
//                } else {
//                    res.add(new ArrayList<>(Arrays.asList(left, right)));
//                    while (lo < hi && nums[lo] == left) lo++;
//                    while (lo < hi && nums[hi] == right) hi--;
//                }
//            }

        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

18.四数之和 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        //首先排序 时间复杂度nlogn 避免后续递归过程中无必要的时间损失
        Arrays.sort(nums);
        return getnSum(nums,4,0,target);
    }
    //一定要明确递归函数的定义(返回的是什么)

    //nSum的通用解法
    //n填写的是想计算的是几数之和,start是从何处开始索引,一般为0,target是求和为多少,本题填0
    public List<List<Integer>> getnSum(int[] nums,int n,int start,int target){
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        //至少是2Sum 且数组大小不应该小于n
        if(n < 2 || len < n){
            return res;
        }
        //当n大于2时的通用情况 递归计算(n-1)Sum问题
        if(n > 2) {
            for(int i = start; i < len ; i++){
                //此时target为原target减去当前遍历的数
                //函数返回的是包含n-1元组的二维列表
                //注意这里start 为 i+1
                List<List<Integer>> sub = getnSum(nums,n - 1,i + 1,target - nums[i]);
                for(List<Integer> arr : sub){
                    arr.add(nums[i]);
                    res.add(arr);
                }
                //边界处理 去重 注意此处比较i的下一项
                while(i < len-1 &&nums[i] == nums[i+1]) i++;
            }
        }
        else if(n == 2){
            //n为2 求两数和问题,双指针
            int left = start;
            int right = len-1;
            while(left < right){
                int sum = nums[left] + nums[right];
                if(sum < target) left++;
                else if(sum > target) right--;
                else{
                    res.add(new ArrayList<>(Arrays.asList(nums[left],nums[right])));
                    while(left < right && nums[left] == nums[left+1]) left++;
                    while(left < right && nums[right] == nums[right-1]) right--;

                    left++;
                    right--;
                }
            }


            // 双指针那一套操作
//            int lo = start, hi = len - 1;
//            while (lo < hi) {
//                int sum = nums[lo] + nums[hi];
//                int left = nums[lo], right = nums[hi];
//                if (sum < target) {
//                    while (lo < hi && nums[lo] == left) lo++;
//                } else if (sum > target) {
//                    while (lo < hi && nums[hi] == right) hi--;
//                } else {
//                    res.add(new ArrayList<>(Arrays.asList(left, right)));
//                    while (lo < hi && nums[lo] == left) lo++;
//                    while (lo < hi && nums[hi] == right) hi--;
//                }
//            }

        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

 Tips:此解法在力扣后续加入特殊用例之后 会导致超出int 将target改为long即可ac

  • 23
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值