首页 > 其他 > 详细

4Sum

时间:2017-11-21 16:19:20      阅读:274      评论:0      收藏:0      [点我收藏+]

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;
    }

4Sum

原文:http://www.cnblogs.com/bingo2-here/p/7873567.html

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