IncredibleThings

导航

LeetCode-4Sum

Given an array S of n integers, are there elements a, b, c, 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: 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) {
        List<List<Integer>> resList = new ArrayList<List<Integer>>();
        if(nums==null || nums.length<4){
            return resList;
        }
        
        Arrays.sort(nums);
        
        int len=nums.length;
        if(nums[0]>0){
            return resList;
        }
        else if(nums[len-1]<0){
            return resList;
        }
        else{
            for(int i=0; i<len-3; i++){
                if(!(i>0 && nums[i]==nums[i-1])){
                    int first=nums[i];
                    for(int j=i+1; j<len-2; j++){
                        if( !(j>i+1 && nums[j] == nums[j-1]) ){
                            int second=nums[j];
                            findTwoNumbers(nums,target,first,second, j+1, resList);
                        }
                    }
                }
            }
        }
        return resList;
    }
    
    public void findTwoNumbers(int[] nums, int target, int first, int second, int start, List<List<Integer>> resList){
        int left=start;
        int right=nums.length-1;
        while(left<right){
            boolean isUnique=true;
            if(left!=start && nums[left]==nums[left-1]){
                left++;
                isUnique=false;
            }
            if(right!=nums.length-1 && nums[right]==nums[right+1]){
                right--;
                isUnique=false;
            }
            if(isUnique){
                if(nums[left]+nums[right]==(target-first-second)){
                    List<Integer> list=new ArrayList<Integer>();
                    list.add(first);
                    list.add(second);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    resList.add(list);
                    //System.out.println(resList.toString());
                    left++;
                    right--;
                }
                else if(nums[left]+nums[right]>(target-first-second)){
                    right--;
                }
                else{
                    left++;
                }
            }
        }
    }
}

  

posted on 2016-07-27 08:10  IncredibleThings  阅读(116)  评论(0)    收藏  举报