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

[lintcode medium]4 sum

时间:2015-12-11 06:51:55      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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.

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)
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.

 

public class Solution {
    /**
     * @param numbers : Give an array numbersbers of n integer
     * @param target : you need to find four elements that‘s sum of target
     * @return : Find all unique quadruplets in the array which gives the sum of
     *           zero.
     */
    public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
        /* your code */
        ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
        if(numbers==null || numbers.length==0) return result;
        int n=numbers.length;
        
        Arrays.sort(numbers);
        for(int i=0;i<n-3;i++)
        {
            if(i!=0&& numbers[i]==numbers[i-1])
            {
                continue;
            }
            for(int j=i+1;j<n-2;j++)
            {
                if(j!=i+1&& numbers[j]==numbers[j-1])
                {
                    continue;
                }
                
                int left=j+1;
                int right=n-1;
                while(left<right)
                {
                   int sum=numbers[i]+numbers[j]+numbers[left]+numbers[right];
                   if(sum==target)
                   {
                     ArrayList<Integer> list=new ArrayList<Integer>();
                     list.add(numbers[i]);
                     list.add(numbers[j]);
                     list.add(numbers[left]);
                     list.add(numbers[right]);
                     result.add(list);
                     left++;
                     right--;
                     while(left<right && numbers[left]==numbers[left-1])
                     {
                       left++;
                     }
                     while(left<right && numbers[right]==numbers[right+1])
                     {
                      right--;
                      }
                   }
                  else if(sum>target)
                  {
                    right--;
                  }
                  else
                  {
                    left++;
                  }
               
                }
            }
        }
        return result;
    }
}

 

[lintcode medium]4 sum

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5037890.html

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