四数之和

博客围绕数组中四数之和问题展开,给定含n个整数的数组和目标值,需判断数组中是否存在四个元素a、b、c、d,使a + b + c + d等于目标值,并找出所有不重复的四元组。其思路是先对数组排序,再固定前两个数字,在剩余数字中查询满足条件的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思路:与处理三数之和一样,先对nums排序,然后固定前两个数字,在剩余的数字中查询满足条件的数字。

代码:

public  List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Set<List<Integer>> set = new HashSet<>();
        if (nums.length < 4){
            return result;
        }
        sort(nums,0,nums.length - 1);
        int sub,k,j;
        for (int i = 0; i< nums.length - 3;i++){
            for (int m = i + 1;m < nums.length - 2;m ++){
                sub = target - nums[i] - nums[m];
                k = m + 1;
                j = nums.length - 1;
                while (k < j){
                    int s = nums[k] + nums [j];
                    if (s == sub){
                        ArrayList<Integer> temp = new ArrayList<>();
                        temp.add(nums[i]);
                        temp.add(nums[m]);
                        temp.add(nums[k]);
                        temp.add(nums[j]);
                        set.add(temp);
                        k++;
                        j--;
                    }else if (sub < s){
                        j --;
                    }else {
                        k ++;
                    }
                }

            }
        }
        result.addAll(set);
        return result;
    }
    public void sort(int[] a,int low,int high ){
        int start = low;
        int end = high;
        int key = a[low];

        if (high > low ) {
            while (start != end) {
                while (end > start && a[end] >= key) {
                    end --;
                }
                if (start < end) {
                    a[start] = a[end];
                    start ++;
                }
                while (end > start && a[start] <= key) {
                    start ++;
                }
                if (start < end) {
                    a[end] = a[start];
                    end --;
                }

            }
            a[start] = key;

            if (start - 1 >= 0) {
                sort(a, low, start - 1);
            }
            if (start + 1 < high) {
                sort(a, start + 1, high);
            }
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值