首页 > 代码库 > LeetCode 4Sum

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


 1 public class Solution { 2     public List<List<Integer>> fourSum(int[] num, int target) { 3         List<List<Integer>> ret = new ArrayList<List<Integer>>(); 4         if (num==null||num.length<4) return ret; 5         int n=num.length; 6         Arrays.sort(num); 7         int i,j,start,end,sum; 8         for (i = 0; i < n-3; i++) { 9             for (j = i+1; j <n-2 ; j++) {10                 start=j+1;11                 end=n-1;12                 while (start < end) {13                     sum = num[start] + num[end];14                     if (sum < target - num[i] - num[j]) {15                         start++;16                     }else if (sum > target - num[i] - num[j]) {17                         end--;18                     } else {19                         ArrayList<Integer> list = new ArrayList<Integer>();20                         list.add(num[i]);21                         list.add(num[j]);22                         list.add(num[start]);23                         list.add(num[end]);24                         ret.add(list);25                         start++;26                         end--;27                         while(end>start && num[start-1]==num[start])++start;28                         while (end>start && num[end+1]==num[end]) --end;29                     }30                 }31                 while (j<n-1&&num[j]==num[j+1]) ++j;32 33             }34             while (i<n-1&&num[i]==num[i+1]) ++i;35         }36         return ret;37     }38 }

 

LeetCode 4Sum