[LintCode/LeetCode] 4Sum

NO IMAGE

Problem

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.

Notice

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.

Example

Given array S = {1 0 -1 0 -2 2}

Note

和3Sum方法一樣,多一個數,故多一層迴圈。完全一致,不再贅述,

Solution

public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] A, int target) {
int n = A.length;
ArrayList<ArrayList<Integer>> res = new ArrayList();
Arrays.sort(A);
for (int i = 0; i < n-3; i  ) {
if (i != 0 && A[i] == A[i-1]) continue;
for (int j = i 1; j <= n-3; j  ) {
if (j != i 1 && A[j] == A[j-1]) continue;
int left = j 1, right = n-1;
while (left < right) {
int sum = A[i] A[j] A[left] A[right];
if (sum == target) {
ArrayList<Integer> temp = new ArrayList();
temp.add(A[i]);
temp.add(A[j]);
temp.add(A[left]);
temp.add(A[right]);
res.add(temp);
left  ;
right--;
while (left < right && A[left] == A[left-1]) left  ;
while (left < right && A[right] == A[right 1]) right--;
}
else if (sum < target) left  ;
else right--;
}
}
}
return res;
}
}