fourSum

Posted athony

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fourSum相关的知识,希望对你有一定的参考价值。

18. 四数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author athonyw
 * @version init
 * @date 2020/6/25 9:21 上午
 */
// 参考三数之和进行解答即可
public class fourSum {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int len = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        if(len < 4) return res;
        for(int i=0;i<=len-4;i++){
            if(i>0 && nums[i] == nums[i-1]) continue;
            int min = nums[i] + nums[i+1] + nums[i+2] + nums[i+3];
            if(min > target) break;
            int max = nums[i] + nums[len-1] + nums[len-2] + nums[len-3];
            if(max < target) continue;
            for(int j=i+1;j<=len-3; j++){
                if(j>i+1 && nums[j] == nums[j-1]) continue;
                int l = j+1;
                int r = len-1;
                while(l<r){
                    int sum = nums[i] + nums[j] + nums[l] + nums[r];
                    if(sum == target){
                        res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
                        while (l < r && nums[l] == nums[l + 1]) l++;
                        while (l < r && nums[r] == nums[r - 1]) r--;
                        l++;
                        r--;
                    }else if(sum < target){
                        l++;
                    }else{
                        r--;
                    }
                }
            }
        }
        return res;
    }
}

以上是关于fourSum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 18. 四数之和

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板