码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode 18]4Sum

时间:2015-09-02 23:14:42      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

1 题目:

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)

2 思路

首先,得理解3Sum。

然后按照3Sum的思路,就好做了。主要是要遍历所有的四个组合。排序是肯定的。详情见代码吧,自己想的。。时间复杂度o(n^3)做了几题,感觉有点状态了。

 

3 代码

    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        int len = nums.length;
        if(len < 4){
            return result;
        }
        
        Arrays.sort(nums);
        int head = 0;
        int end = len-1;
        while(head < end -2){
            while(head < end-2){
                int pre = head + 1;
                int suffix = end - 1;
                /*  compare all four group between pre & suffic   */
                while(pre < suffix){
                    int sum = nums[head]+nums[end]+nums[pre]+nums[suffix];
                    if(sum < target){
                        ++pre;
                    }else if(sum > target){
                        --suffix;
                    }else{
                        result.add(Arrays.asList(nums[head],nums[pre],nums[suffix],nums[end]));
                        ++pre;
                        --suffix;
                        while(pre <= suffix && nums[pre]==nums[pre-1]) ++pre;
                        while(pre <= suffix && nums[suffix]==nums[suffix+1]) --suffix;
                    }
                }
                /* for each nums[head], compore all nums[head] until head<end-2 */
                ++head;
                while(head<end-2 && nums[head]==nums[head-1]) ++head;
            }
            /* set head to 0 & end-1 ,so we can traverse all four groups */
            head=0;
            --end;
            while(head<end-2 &&nums[end] == nums[end+1]) --end;
        }
    
        return result;
    }

 

[leetcode 18]4Sum

标签:

原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4779531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!