[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:
- 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:
O(n^3)的Time Efficiency.
1 public class Solution { 2 public List<List<Integer>> fourSum(int[] num, int target) { 3 List<List<Integer>> result=new ArrayList<List<Integer>>(); 4 Arrays.sort(num); 5 for(int i=0;i<num.length-3;++i){ 6 if(i>0&&num[i]==num[i-1]) 7 continue; 8 for(int j=i+1;j<num.length-2;++j){ 9 if(j>i+1&&num[j]==num[j-1]) 10 continue; 11 int low=j+1; 12 int high=num.length-1; 13 while(low<high){ 14 int sum=num[i]+num[j]+num[low]+num[high]; 15 if(sum==target){ 16 List<Integer> temp=new ArrayList<Integer>(); 17 temp.add(num[i]); 18 temp.add(num[j]); 19 temp.add(num[low]); 20 temp.add(num[high]); 21 result.add(temp); 22 low++; 23 high--; 24 while(low<high&&num[low]==num[low-1]) 25 low++; 26 while(low<high&&num[high]==num[high+1]) 27 high--; 28 } 29 else if(sum<target){ 30 low++; 31 } 32 else 33 high--; 34 } 35 } 36 } 37 return result; 38 } 39 }