[leedcode 18] 4Sum

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

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

 

    For example, given array S = {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 class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        //时间复杂度O(n^3)
        //注意去重
        Arrays.sort(nums);
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        for(int i=0;i<nums.length;i++){
            if(i>0&&nums[i]==nums[i-1])continue;//去重
            for(int j=i+1;j<nums.length;j++){
                if(j>i+1&&nums[j]==nums[j-1])continue;//去重
                int left=j+1;
                int right=nums.length-1;
                int temp=target-nums[i]-nums[j];
                while(left<right){
                    if(temp==nums[left]+nums[right]){
                        List<Integer> seq=new ArrayList<Integer>();
                        seq.add(nums[i]);
                        seq.add(nums[j]);
                        seq.add(nums[left++]);
                        seq.add(nums[right--]);
                        res.add(seq);
                        while(left<right&&nums[left-1]==nums[left])left++;//去重
                    }else{
                        if(temp>nums[left]+nums[right]){
                            left++;
                        }else right--;
                                                
                    }                                        
                    
                }
                
            }
        }
                        return res;
    }
}

 

你可能感兴趣的:(code)