[18] LeetCode four and the number of

Topic rating: 4Sum (Medium)

Subject description:

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

  The meaning of problems: Given an array containing n integers nums target and a target value, determines whether or not there are four elements a, b, c, and D nums such that a + b + c + d is equal to the value of the target? Identify all satisfy the conditions of the quad and do not repeat.


Problem-solving ideas:

  This is nothing special, and direct reference to three digital sum of: [15] LeetCode three and the number of 0

  Online there is no other particular solution is found, there is that using half way into the sum of two and two, but feel too cumbersome, not intuitive, and here it is used directly in the outer layer and the number of three-plus the one cycle, the time complexity is: O (n ^ 3).

  Then such practice mainly to make a summary:

  Two numbers and range , practice:

  Three and the number of (N number of sum) sequence practice:

  • Step: java.util.Arrays.sort (int [] nums), ascending
  • The second step: N-2 layer for loop, plus two bidirectional pointers, after a while loop bidirectional pointer for an array closer to the center, while the circle of two nested while loops, for deduplication
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res=new ArrayList<>();
        if(nums==null && nums.length==0)
            return res;
        Arrays.sort(nums);
        int len=nums.length;
        for(int i=0;i<len-3;i++){
            if(i>0 && nums[i-1]==nums[i]) //跳过重复的
                continue; 
            for(int j=i+1;j<len-2;j++){
                if(j>i+1 && nums[j]==nums[j-1])  //跳过重复的
                    continue;
                int low=j+1,high=len-1,sum=target-nums[i]-nums[j];
                while(low<high){
                    if(nums[low]+nums[high]==sum){ //找到一个解
                        res.add(Arrays.asList(nums[i],nums[j],nums[low],nums[high]));
                        while(low<high && nums[low+1]==nums[low])
                            low++;
                        while(low<high && nums[high-1]==nums[high])
                            high--;
                        low++;
                        high--;
                    }else if(nums[low]+nums[high]<sum)
                        low++;
                    else
                        high--;
                }
            }
        }
        return res;
    }
}

Guess you like

Origin www.cnblogs.com/gzshan/p/11129595.html