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

[leedcode 18] 4Sum

时间:2015-07-07 16:38:17      阅读:86      评论: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)

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        //时间复杂度O(n^3)
        //注意去重
        Arrays.sort(nums);
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        for(int i=0;i<nums.length;i++){
            if(i>0&&nums[i]==nums[i-1])continue;//去重
            for(int j=i+1;j<nums.length;j++){
                if(j>i+1&&nums[j]==nums[j-1])continue;//去重
                int left=j+1;
                int right=nums.length-1;
                int temp=target-nums[i]-nums[j];
                while(left<right){
                    if(temp==nums[left]+nums[right]){
                        List<Integer> seq=new ArrayList<Integer>();
                        seq.add(nums[i]);
                        seq.add(nums[j]);
                        seq.add(nums[left++]);
                        seq.add(nums[right--]);
                        res.add(seq);
                        while(left<right&&nums[left-1]==nums[left])left++;//去重
                    }else{
                        if(temp>nums[left]+nums[right]){
                            left++;
                        }else right--;
                                                
                    }                                        
                    
                }
                
            }
        }
                        return res;
    }
}

 

[leedcode 18] 4Sum

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4627081.html

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