LeetCode18 4Sum

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

public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for(int i = 0; i < nums.length - 3; i++){
            for(int j = i+1; j < nums.length - 2; j++){
                int sum = target - nums[i] - nums[j];
                int front =  j + 1;
                int back = nums.length - 1;
                while(front < back){
                    if(nums[front] + nums[back] == sum){
                        res.add(Arrays.asList(nums[i],nums[j],nums[front],nums[back]));
                        while(front < back && nums[front+1] == nums[front]) front++;
                        while(front < back && nums[back-1] == nums[back]) back--;
                        front++;
                        back--;
                    }
                    else if(nums[front] + nums[back] < sum){
                        front++;
                    }else{
                        back--;
                    }
                }
                while(j+1 < nums.length-2 && nums[j+1] == nums[j]) j++;
            }
            while(i+1 < nums.length-3 && nums[i+1] == nums[i]) i++;
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/85000974
今日推荐