Wednesday, January 7, 2015

LeetCode 18: 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.
Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, abcd)
  • 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[] num, int target) {
        List<List<Integer>> result = new LinkedList<>();
        
        int n = num.length;
        
        if (n < 4)
            return result;
            
        // Step 1: Sort num array
        Arrays.sort(num);
        
        // Step 2: Move two pointers from left and right, respectively.
        int left, right; // Left and right pointers
        
        for (int i = 0; i < n-3; i++)
        {
            for (int j = i+1; j < n-2; j++)
            {
                left = j+1;
                right = n-1;
                
                while (left < right)
                {
                    int tmp = num[i] + num[j] + num[left] + num[right];
                    
                    if (tmp < target)
                        left++;
                    else if (tmp > target)
                        right--;
                    else
                    {
                        List<Integer> ret = new LinkedList<>();
                        ret.add(num[i]);
                        ret.add(num[j]);
                        ret.add(num[left]);
                        ret.add(num[right]);
                        
                        if (!result.contains(ret))
                            result.add(ret);
                        
                        // Note: Move two pointers. Don't use "break;" in case miss some pairs.
                        left++;
                        right--;
                    }
                }
            }
        }
        
        return result;
    }
}

No comments:

Post a Comment