LeetCode 18. 4Sum 四数之和(Java)

题目:

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:
The solution set must not contain duplicate quadruplets.

Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

解答:

本题与计算三数之和方法基本一致,只是改为双重循环嵌套。通过双重循环,将四数之和改为三数之和,将三数之和改为两数之和,最后采用双指针进行求解。
其中,注意去重操作的处理。

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 len = nums.length;
        for(int i=0; i<len-3; i++) {
        	//去重,避免重复
            if(i!=0 && nums[i] == nums[i-1]) {
                continue;
            }
            //若最小四数之和 > target,则直接break
            if(nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) {
                break;
            }
            //若当前i与最大三数之和 < target,则当前i不可实现,直接continue进行下一循环判断
            if(nums[i] + nums[len-1] + nums[len-2] + nums[len-3] < target) {
                continue;
            }
            
            for(int j=i+1; j<len-2; j++) {
            	//去重
                if(j>i+1 && nums[j] == nums[j-1]) {
                    continue;
                }
                //若最小四数之和 > target,则直接break
                if(nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) {
                    break;
                }
                //若当前i,j与最大两数之和 < target,则当前i,j不可实现,直接continue进行下一循环判断
                if(nums[i] + nums[j] + nums[len-1] + nums[len-2] < target) {
                    continue;
                }
                int left = j+1;
                int right = len-1;
                while(left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if(sum == target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        //去重
                        while(left<right && nums[left] == nums[left+1]) {
                            left++;
                        }
                        //去重
                        while(left<right && nums[right] == nums[right-1]) {
                            right--;
                        }
                        left++;
                        right--;
                    }
                    if(sum < target) {
                        left++;
                    }
                    if(sum > target) {
                        right--;
                    }
                }
            }
        }
        return res;
    }
}

你可能感兴趣的:(LeetCode)