您的位置:首页 > 职场人生

leetcode 4Sum 难度系数3 3.9

2014-01-28 12:07 281 查看
Question:

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, 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 {

private ArrayList<ArrayList<Integer>> results;

public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
results = new ArrayList<ArrayList<Integer>>();
if (num.length < 4) {
return results;
}
Arrays.sort(num);
int length = num.length - 1;
for (int i = 0; i <= length - 3; i++) {
if (i != 0 && num[i] == num[i - 1]) {
continue;
}
for (int j = i + 1; j <= length - 2; j++) {
if (j != i + 1 && num[j] == num[j - 1]) {
continue;
}
subFourSum(num, i, j, j + 1, length, target);
}
}
return results;

}

private void subFourSum(int[] num, int i, int j, int first, int last,
int target) {
while (first < last) {
int sum = num[i] + num[j] + num[first] + num[last];
if (sum > target) {
last--;
} else if (sum < target) {
first++;
} else if (sum == target) {
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(num[i]);
result.add(num[j]);
result.add(num[first]);
result.add(num[last]);
results.add(result);
first++;
last--;
while (first < last && num[first] == num[first - 1]) {
first++;
}
while (first < last && num[last] == num[last + 1]) {
last--;
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 面试