LeetCode 18. 四数之和

题目链接

18. 四数之和

题目分析

这个题没啥好说的,就是四数之和拆分成三数之和,然后三数之和固定一个边界值,在剩下的部分利用双指针寻找符合条件的值即可。
这个题主要是可以优化的地方很多,很多剪枝的地方还学不会,第一次做出来只击败了10%的人,慢的可怜,后来加入了最小值和最大值的判断,把整个算法优化到击败60%的人。

代码实现

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length < 4){
            return res;
        }
        Arrays.sort(nums);
        //如果最小值比target大或者最大值比target小,说明不存在这种四数之和,直接返回
        int minValue = nums[0] + nums[1] + nums[2] + nums[3];
        int maxValue = nums[nums.length - 1] + nums[nums.length - 2] + nums[nums.length - 3] + nums[nums.length - 4];
        if (minValue > target || maxValue < target) {
            return res;
        }
        int i = 0;
        while(i < nums.length - 3){
            int j = i + 1;
            while(j < nums.length - 2){
                int num = target - nums[i] - nums[j];
                int left = j + 1;
                int right = nums.length - 1;
                while(left < right){
                    if(nums[left] + nums[right] < num){
                        int temp = nums[left];
                        while(left < nums.length - 1 && nums[left]  == temp){
                            left++;
                        }
                    }else if(nums[left] + nums[right] > num){
                        int temp =  nums[right];
                        while(right > left && nums[right] == temp){
                            right--;
                        }
                    }else if(nums[left]  + nums[right] == num){
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        res.add(list);
                        int temp = nums[left];
                        while(left < nums.length - 1 && nums[left]  == temp){
                            left++;
                        }
                        temp = nums[right];
                        while(right > left && nums[right] == temp){
                            right--;
                        }
                    }
                }
                int temp = nums[j];
                while(j < nums.length - 2 && nums[j] == temp){
                    j++;
                }
            }
            int temp = nums[i];
            while(i < nums.length - 3 && nums[i] == temp){
                i++;
            }
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/ZJPaang/p/13369368.html