18. 【中等】四数之和

18. 【中等】四数之和


链接

题目描述

在这里插入图片描述

双指针

思路

在【三数和】双指针的基础上,添加了判断

  • 当前最小值和 target :如果当前最小值 > target ,直接往后走
  • 当前最大值和 target :如果当前最大值 < target ,直接往后走

代码

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums == null || nums.length < 4){
            return res;
        }
        Arrays.sort(nums);//排序,小的在前,大的在后
        int length = nums.length;
        for(int i = 0 ; i < nums.length-3 ;i++){
            //如果重复了,就跳过
            if(i != 0 && nums[i] == nums[i-1]){
                continue;
            }
            //计算当前最小值,如果最小值都比target要大,不可能
            int curMin = nums[i]+nums[i+1]+nums[i+2]+nums[i+3];
            if(curMin > target){
                continue;
            }
            //计算当前最大值,如果当前最大值都比target要小,不可能
            int curMax = nums[i]+nums[length-1]+nums[length-2]+nums[length-3];
            if(curMax < target){
                continue;
            }
            //下一层循环
            for(int j = i+1; j < length-2 ;j++){
                //排除重复
                if(j != i+1 && nums[j]==nums[j-1]){
                    continue;
                }
                //当前最小值
                curMin = nums[j]+nums[j+1]+nums[j+2];
                if(curMin > target-nums[i]){
                    continue;
                }
                //当前最大值
                curMax = nums[j]+nums[length-1]+nums[length-2];
                if(curMax < target-nums[i]){
                    continue;
                }
                
                int l = j+1;
                int r = length-1;
                int sum = nums[i]+nums[j]+nums[l]+nums[r];
                while(l < r){
                    sum = nums[i]+nums[j]+nums[l]+nums[r];
                    if(sum == target){
                        res.add(Arrays.asList(nums[i],nums[j],nums[l],nums[r]));
                        l++;
                        r--;
                        while(l<r && nums[l] == nums[l-1]){
                            l++;
                        }
                        while(l<r && nums[r] == nums[r+1]){
                            r--;
                        }
                    }else if(sum > target){
                        r--;
                    }else{
                        l++;
                    }
                }
            }
        }
        return res;
    }
}
发布了55 篇原创文章 · 获赞 1 · 访问量 884

猜你喜欢

转载自blog.csdn.net/weixin_42469108/article/details/103615200