4Sum

4Sum

问题:

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.

思路:

  双指针问题的扩展

我的代码:

public class Solution {
    public List<List<Integer>> fourSum(int[] num, int target) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        if(num == null || num.length < 4)   return list;
        int len = num.length;
        Arrays.sort(num);
        for(int i = 0; i <= len - 4; i++)
        {
            if(i == 0 || !(i != 0 && num[i] == num[i-1]))
            {
                for(int j = i + 1; j <= len - 3; j++)
                {
                    if(j == i + 1 || !(j != i+ 1 && num[j] == num[j-1]))
                    {
                        int left = j + 1;
                        int right = len - 1;
                        while(left < right)
                        {
                            int val = num[i] + num[j] + num[left] + num[right];
                            if(val == target)
                            {
                                List<Integer> tmpList = new ArrayList<Integer>();
                                tmpList.add(num[i]);
                                tmpList.add(num[j]);
                                tmpList.add(num[left]);
                                tmpList.add(num[right]);
                                list.add(tmpList);
                                left++;
                                right--;
                                while(left < right && num[left] == num[left-1])
                                {
                                    left++;
                                }
                                while(left < right && num[right] == num[right+1])
                                {
                                    right--;
                                }
                             }
                            else if(val > target)
                            {
                                right --;
                            }
                            else 
                                left ++;
                        }
                    }
                }
            }
        }
        return list;
    }
}
View Code

学习之处:

  • 避免重复的关键之处在于:
 while(left < right && num[left] == num[left-1])
{
    left++;
}

 

posted on 2015-04-01 21:14  zhouzhou0615  阅读(123)  评论(0编辑  收藏  举报

导航