2015年9月18日星期五

Leetcode 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)

Solution 1: Similar as 3 Sum, time complex is O(n^3)
 public class Solution {  
   public List<List<Integer>> fourSum(int[] nums, int target) {  
     List<List<Integer>> res=new ArrayList<>();  
     int n=nums.length;  
     if (n<4) return res;  
     Arrays.sort(nums);  
     //if (nums[0]>target || nums[n-1]<target) return res;//this need to removed!!  
     for (int i=0; i<n-3; i++) {  
       if (i>0 && nums[i]==nums[i-1]) continue;  
       for (int j=i+1; j<n-2; j++) {  
         if (j>i+1 && nums[j]==nums[j-1]) continue;  
         int lo=j+1, hi=n-1;  
         while (lo<hi) {  
           int sum=nums[i]+nums[j]+nums[lo]+nums[hi];  
           if (sum>target) hi--;  
           else if (sum<target) lo++;  
           else {  
             res.add(Arrays.asList(nums[i],nums[j],nums[lo],nums[hi]));  
             int k=lo+1;  
             while (k<hi && nums[k]==nums[lo]) k++;  
             lo=k;  
           }  
         }  
       }  
     }  
     return res;  
   }  
 }  

没有评论:

发表评论