Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example:
Given array nums = [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铁追。http://www.reibang.com/p/4bc0920417bb
Java語言:
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < len - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {//防止重復
continue;
}
for (int j = i + 1; j < len - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {//防止重復
continue;
}
int lo = j + 1, hi = len - 1;
while (lo < hi) {
int sum = nums[i] + nums[j] + nums[lo] + nums[hi];
if (sum == target) {
res.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi]));
while (lo < hi && nums[lo] == nums[lo + 1]) {//防止重復
lo++;
}
while (lo < hi && nums[hi] == nums[hi - 1]) {
hi--;
}
lo++;
hi--;
} else if (sum < target) {
lo++;
} else {
hi--;
}
}
}
}
return res;
}