0
点赞
收藏
分享

微信扫一扫

18. 四数之和

沐之轻语 2022-02-07 阅读 72

给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):

0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案

使用排序+双指针法,和三数之和一个套路甚至一个模板,在确定1,2个数后锁定3,4数的结果,并进行比对,如果大就将fourth的指针前移来缩小结果,如果third 和fourth指针重合,则判定此third不满足条件(此后third没有移动的必要,属于剪枝操作)。

public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ans=new ArrayList<>();
        Arrays.sort(nums);
        int len=nums.length;
        for (int first = 0; first < len-3; first++) {
            if(first>0&&nums[first]==nums[first-1]){
                continue;
            }
            for (int second = first+1; second < len-2; second++) {
                if(second>first+1&&nums[second]==nums[second-1]){
                    continue;
                }
                int tmp=target-nums[first]-nums[second];
                int fourth=len-1;
                for (int third = second+1; third < len-1; third++) {
                    if(third>second+1&&nums[third]==nums[third-1]){
                        continue;
                    }
                    while (third<fourth&&nums[third]+nums[fourth]>tmp){
                        fourth--;
                    }
                    if(fourth==third){
                        break;
                    }
                    if(nums[third]+nums[fourth]==tmp){
                        List<Integer> res=new ArrayList<>();
                        res.add(nums[first]);
                        res.add(nums[second]);
                        res.add(nums[third]);
                        res.add(nums[fourth]);
                        ans.add(res);
                    }
                }
            }
        }
        return ans;
    }
举报

相关推荐

0 条评论