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

题解:参考3Sum,把4Sum问题转换成3Sum,再转换成2Sum,如下图所示:

【leetcode刷题笔记】4Sum

代码如下:

 1 public class Solution {

 2     public List<List<Integer>> fourSum(int[] num, int target) {

 3         List<List<Integer>> answer = new ArrayList<List<Integer>>();

 4         if(num == null || num.length == 0)

 5             return answer;

 6         

 7         Arrays.sort(num);

 8         int length = num.length;

 9         for(int i = 0;i < length;i++){

10             if(i!=0 && num[i]== num[i-1] )

11                 continue;

12             for(int j = i+1;j < length;j++ ){

13                 if(j != i+1 && num[j] == num[j-1] )

14                     continue;

15                 int start = j + 1;

16                 int last = length - 1;

17                 while(start < last){

18                     int sum = num[i]+num[j]+num[start]+num[last];

19                     if(sum == target){

20                         ArrayList<Integer> result = new ArrayList<Integer>();

21                         result.add(num[i]);

22                         result.add(num[j]);

23                         result.add(num[start]);

24                         result.add(num[last]);

25                         answer.add(result);

26                         start++;

27                         last--;

28                         while(start < last && num[start-1] == num[start])

29                             start++;

30                     }

31                     else if(sum < target){

32                         start++;

33                     }

34                     else {

35                         last--;

36                     }

37                 }

38             }

39         }

40         return answer;

41     }

42 }

你可能感兴趣的:(LeetCode)