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: 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]
]
解法
在3sum的基础上再包一层循环m,m从左往右,i = m + 1,j = i + 1, k = nums.length - 1.
注意数据越界问题,i以m为基准。
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
if (nums.length == 0 && nums == null) {
return null;
}
List<List<Integer>> result = new LinkedList<>();
Arrays.sort(nums);
int i = 0, m = 0;
while (m < nums.length - 3) {
while (m != 0 && (m > 0 && nums[m] == nums[m - 1]) && m < nums.length - 3) {
m++;
}
i = m + 1;
while (i < nums.length - 2) {
// 小心数组越界,i以m为基准,如果没有m,i > 1 && nums[i] == nums[i - 1] && i < nums.length - 2
while (i > m + 1 && nums[i] == nums[i - 1] && i < nums.length - 2) {
i++;
}
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
List<Integer> temp = new ArrayList<>();
// 小心数组越界
while (nums[m] + nums[i] + nums[j] + nums[k] < target && j < k) {
j++;
}
// 小心数组越界
while (nums[m] + nums[i] + nums[j] + nums[k] > target && j < k) {
k--;
}
// 小心数组越界
if (nums[m] + nums[i] + nums[j] + nums[k] == target && j < k) {
// 小心数组越界
while (j < k && nums[j] == nums[j + 1]) j++;
// 小心数组越界
while (j < k && nums[k] == nums[k - 1]) k--;
result.add(Arrays.asList(nums[m], nums[i], nums[j], nums[k]));
j++;
k--;
}
}
i++;
}
m++;
}
return result;
}
}