您的位置:首页 > 其它

18. 4Sum

2017-12-22 18:17 447 查看
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: 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]
]


class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length < 4) {
return res;
}

Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}

int sum3 = target - nums[i];  // 后3个数之和需等于sum3
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}

int sum2 = sum3 - nums[j];  // 后2个数之和需等于sum3
int left = j + 1, right = nums.length - 1;

while (left < right) {
if (nums[left] + nums[right] == sum2) {
List<Integer> quad = new ArrayList<>();
quad.add(nums[i]);
quad.add(nums[j]);
quad.add(nums[left]);
quad.add(nums[right]);
res.add(quad);

while (left < right && nums[left++] == nums[left]) {}
while (left < right && nums[right--] == nums[right]) {}

} else if (nums[left] + nums[right] < sum2) {
while (left < right && nums[left++] == nums[left]) {}

} else {
while (left < right && nums[right--] == nums[right]) {}
}
}
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: