4 sum

4 sum

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]
]

Thoughts:

Using the same idea used in 3 sum, and I transferred from the 3sum version.

The idea is to make sure each number would not repeat itself in the next for loop.

class Solution {
    public List> fourSum(int[] nums, int target) {
        List> lst = new ArrayList<>();
        Arrays.sort(nums);
        for(int j = 0; j < nums.length-2; j++) {
            if(j == 0 || (nums[j] != nums[j-1])) {
                for(int i = j+1; i< nums.length-1; i++) {
                    if(i == j+1 ||(nums[i] != nums[i-1])) {
                        int lo = i+1, hi = nums.length-1, sum = target-nums[i]-nums[j];
                        while(lo < hi) {
                            if(nums[lo]+nums[hi] == sum) {
                                lst.add(Arrays.asList(nums[j], nums[i], nums[lo], nums[hi]));
                                while(lo < hi && nums[lo] == nums[lo+1]) lo++;
                                while(hi > lo && nums[hi] == nums[hi-1]) hi--;
                                lo++; hi--;
                            }
                            else if(nums[lo]+nums[hi] < sum) {
                                lo++;
                            }else {
                                hi--;
                            }
                        }
                    }
                }
            }

        }
        return lst;
            
    }
}

你可能感兴趣的:(4 sum)