首页 > 其他 > 详细

leetcode--4Sum

时间:2014-03-22 07:51:15      阅读:182      评论:0      收藏:0      [点我收藏+]

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)

The algorithm is similar to 3Sum.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Solution {
    public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
        ArrayList<ArrayList<Integer> > result = new ArrayList<ArrayList<Integer> >();
        int len = num.length;
        if(len >=4){
            // sort array first
            Arrays.sort(num);
            for(int i = 0; i < len - 3; ++i){
                int j = i + 1;
                int sum = target - num[i];
                while(j < len - 2){
                    int mid = j + 1;
                    int end = len - 1;
                    while(mid < end){
                        int tripleSum = num[j] + num[mid] + num[end];
                        if(tripleSum == sum){
                            ArrayList<Integer> oneSolution = new ArrayList<Integer>();
                            oneSolution.add(num[i]);
                            oneSolution.add(num[j]);
                            oneSolution.add(num[mid]);
                            oneSolution.add(num[end]);
                            result.add(oneSolution);                       
                        }
                        else if(tripleSum < sum){
                            ++mid;
                            continue;
                        }
                        else{
                            --end;
                            continue;
                        }                   
                        ++mid;
                        --end;
                        while(mid < end && num[mid - 1] == num[mid])
                            ++mid;
                        while(mid < end && num[end] == num[end + 1])
                            --end;
                    }
                    ++j;
                    while(j < len - 2 && num[j - 1] == num[j])
                        ++j;
                }
                while(i < len - 3 && num[i] == num[i + 1])
                    ++i;           
            }
        }
        return result;   
    }
}

  

leetcode--4Sum,布布扣,bubuko.com

leetcode--4Sum

原文:http://www.cnblogs.com/averillzheng/p/3617061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!