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: 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]
]

public List<List<Integer>> fourSum(int[] nums, int target) {
        int length = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> lists = new ArrayList<>();
        for (int i = 0; i < length-3; i++) {
            if (i>0&&nums[i] == nums[i-1]){
                continue;
            }
            for (int j=i+1; j < length-2;j++){
                if (j>i+1&&nums[j]==nums[j-1]){
                    continue;
                }
                int head = j+1;
                int tail = length-1;

                while (head<tail){
                    int tmp = nums[i]+nums[j]+nums[head]+nums[tail];
                    if (tmp<target){
                        head++;
                    }
                    else if (tmp>target){
                        tail--;
                    }
                    else {
                        lists.add(Arrays.asList(nums[i],nums[j],nums[head],nums[tail]));

                        int k = head+1;
                        while (k<tail&&nums[k]==nums[k-1]){
                            k++;
                        }
                        head = k;

                        int l = tail-1;
                        while (l>head&&nums[l]==nums[l+1]){
                            l--;
                        }
                        tail = l;
                    }
                }
            }
        }
        return lists;
    }
posted @ 2017-11-21 15:55  binryang  阅读(103)  评论(0编辑  收藏  举报