四数之和 java实现

四数之和

问题描述:

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

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

示例 1:

输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:

输入:nums = [], target = 0
输出:[]

思路:

和三数之和类似,先套用两层循环,然后双重指针左右来查询。
注意的点是第二层i 如果等于第一层的q是不用跳过循环的

代码:

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
         List<List<Integer>> a= new  LinkedList<List<Integer>>();
        Arrays.sort(nums,0,nums.length);
        int len=nums.length;
        if(len<4) return a;
        for(int q=0;q<len;q++){
            for(int i=q+1;i<len;i++){


                if (q > 0 && nums[q] == nums[q - 1]) continue;
                if (i > 0 && nums[i] == nums[i - 1]&&i-1!=q) continue;
                int t = target-nums[q]-nums[i];

                int j = i + 1, k = len - 1;
                while (j < k) {
                    if (nums[j] + nums[k] > t) {
                        k--;
                    } else if (nums[j] + nums[k] < t) {
                        j++;
                    } else {
                        // find
                        List<Integer> ans = new LinkedList<>();
                        ans.add(nums[q]);
                        ans.add(nums[i]);
                        ans.add(nums[j]);
                        ans.add(nums[k]);
                        a.add(ans);
                        // 去除临近相同的元素
                        while (j < k && nums[j] == nums[j + 1]) j++;
                        while (j < k && nums[k] == nums[k - 1]) k--;
                        j++;
                        k--;
                    }
                }
            }
        }
        return a;
    }
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值