2014年11月2日星期日

[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)
The same idea with 3sum.

public class Solution {
    public List<List<Integer>> fourSum(int[] num, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        int n = num.length;
        if(n < 4)
            return res;
        Arrays.sort(num);
        int pre = num[0];
        for(int i = 0; i < n-3; i++) {
            if(i > 0 && pre == num[i])
                continue;
            pre = num[i];
            int npre = num[i+1];
            for(int j = i+1; j < n-2; j++) {
                if(j > i+1 && npre == num[j])
                    continue;
                npre = num[j];
                int left = j + 1;
                int right = n - 1;
                while(left < right) {
                    int sum = num[i] + num[j] + num[left] + num[right];
                    if(sum == target) {
                        ArrayList<Integer> list = new ArrayList<Integer>();
                        list.add(num[i]); list.add(num[j]);
                        list.add(num[left]); list.add(num[right]);
                        res.add(list);
                        left++;
                        while(left < right && num[left] == num[left-1])
                            left++;
                    }
                    else if(sum > target) {
                        right--;
                        while(left < right && num[right] == num[right+1])
                            right--;
                    }
                    else {
                        left++;
                        while(left < right && num[left] == num[left-1])
                            left++;
                    }
                }
            }
        }
        return res;
    }
}

没有评论:

发表评论