18 4Sum 四数之和
Description:
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]
]
题目描述:
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例 :
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
思路:
参考LeetCode #15 3Sum 三数之和, 先排序, target可以转化为 -a, 就转换为 3Sum, 双重循环中用双指针查找
时间复杂度O(n ^ 3), 空间复杂度O(1)
代码:
C++:
class Solution
{
public:
vector> fourSum(vector& nums, int target)
{
int n = nums.size();
vector> result;
if (n < 3) return result;
sort(nums.begin(), nums.end());
for (int i = 0; i < n; i++)
{
if (i > 0 and nums[i] == nums[i - 1]) continue;
int t1 = target - nums[i];
for (int j = i + 1; j < n; j++)
{
if (j > i + 1 and nums[j] == nums[j - 1]) continue;
int t2 = t1 - nums[j], l = j + 1, r = n - 1;
while (l < r)
{
if (nums[l] + nums[r] > t2) --r;
else if (nums[l] + nums[r] < t2) ++l;
else
{
result.push_back({nums[i], nums[j], nums[l++], nums[r--]});
while (l < r and nums[l] == nums[l - 1]) ++l;
while (l < r and nums[r] == nums[r + 1]) --r;
}
}
}
}
return result;
}
};
Java:
class Solution {
public List> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List> result = new ArrayList<>();
int n = nums.length;
if (n < 3) return result;
for (int i = 0; i < n; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int t1 = target - nums[i];
for (int j = i + 1; j < n; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int t2 = t1 - nums[j], l = j + 1, r = n - 1;
while (l < r) {
if (nums[l] + nums[r] > t2) --r;
else if (nums[l] + nums[r] < t2) ++l;
else {
result.add(Arrays.asList(nums[i], nums[j], nums[l++], nums[r--]));
while (l < r && nums[l] == nums[l - 1]) ++l;
while (l < r && nums[r] == nums[r + 1]) --r;
}
}
}
}
return result;
}
}
Python:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
result, n = [], len(nums)
if sum(nums[:4]) > target or n < 3:
return result
for i in range(n):
if i > 0 and nums[i] == nums[i - 1]:
continue
t1 = target - nums[i]
for j in range(i + 1, n):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
t2, l, r = t1 - nums[j], j + 1, n - 1
while l < r:
if nums[l] + nums[r] > t2:
r -= 1
elif nums[l] + nums[r] < t2:
l += 1
else:
result.append([nums[i], nums[j], nums[l], nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
while l < r and nums[r] == nums[r + 1]:
r -= 1
return result