18. 4Sum
Posted 朴素贝叶斯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了18. 4Sum相关的知识,希望对你有一定的参考价值。
题目描述
Given an arrayS
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)
方法1:set去重
代码
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &nums, int target)
{
set<vector<int>> ret;
sort(nums.begin(), nums.end());
for(int i = 0; i <= (int)(nums.size() - 4); ++i)
{
for(int j = i + 1; j <= (int)(nums.size() - 3); ++j)
{
int left = j + 1, right = nums.size() - 1;
while(left < right)
{
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum < target)
++left;
else if (sum > target)
--right;
else
{
vector<int> temp = {nums[i], nums[j], nums[left], nums[right]};
ret.insert(temp);
++left;
--right;
}
}
}
}
return vector<vector<int>>(ret.begin(), ret.end());
}
};
方法2:手动进行去重复处理
代码
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &nums, int target)
{
vector<vector<int>> ret;
sort(nums.begin(), nums.end());
//i直接遍历枚举四元组的第一个数下标
for(int i = 0; i <= int(nums.size() - 4); ++i)
{
if(i > 0 && nums[i] == nums[i - 1])
continue;
//j直接遍历枚举四元组的第二个数下标
for(int j = i + 1; j <= int(nums.size() - 3); ++j)
{
if(j > i + 1 && nums[j] == nums[j - 1])
continue;
int left = j + 1, right = nums.size() - 1;
while(left < right)
{
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if(sum < target)
++left;
else if (sum > target)
--right;
else
{
vector<int> temp = {nums[i], nums[j], nums[left], nums[right]};
ret.push_back(temp);
++left;//下一个候选位置
--right;//下一个候选位置
//对候选位置合法性进行检查
while(left<right && nums[left]==nums[left-1]) ++left;
while(left<right && nums[right]==nums[right+1]) --right;
}
}
}
}
return ret;
}
};
以上是关于18. 4Sum的主要内容,如果未能解决你的问题,请参考以下文章