medium程度题
题目:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]菜鸡没想出来,哎。。参考的别人的解法,先排序,然后夹逼,去重
其实挺简单的,要多想多积累啊。。。。。。
类似的可以拓展为k SUM ,时间复杂度O(max(n㏒n,N^(k - 1)))
AC解:
class Solution
{
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> result;
int size = nums.size();
if (size < 3)
return result;
sort(nums.begin(),nums.end());
const int sum = 0;
auto last = nums.end();
for (auto i = nums.begin(); i < nums.end() - 2; i++)
{
auto j = i + 1;
if (i > nums.begin() && *i == *(i - 1))
continue;
auto k = last - 1;
while (j < k)
{//去重
if (*i + *j + *k > sum)
{
k--;
while (*k == *(k + 1))
k--;
}else if (*i + *j + *k < sum)
{
j++;
while (*j == *(j - 1))
j++;
}else
{
result.push_back({*i,*j,*k});
j++;
k--;
while (*j == *(j - 1) && *k ==*(k + 1) && j < k)
{
j++;
k--;
}
}
}
}
return result;
}
};
类似的,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] ]AC解:
class Solution
{
public:
vector<vector<int>> fourSum(vector<int>& nums, int target)
{
vector<vector<int>> result;
int size = nums.size();
if (size < 4)
return result;
auto first = nums.begin();
auto last = nums.end();
sort(nums.begin(),nums.end());
for (auto i = first; i < last - 3; i++)
{
if (i > first && *i == *(i - 1))
continue;
for (auto j = i + 1; j < last - 2; j++)
{
if (j > i + 1 && *j == *(j - 1))
continue;
auto k = j + 1;
auto l = last - 1;
while (k < l)
{
if (*i + *j + *k + *l > target)
{
l--;
while (*l == *(l + 1))
l--;
}
else if (*i + *j + *k + *l < target)
{
k++;
while (*k == *(k - 1))
k++;
}
else
{
result.push_back({*i,*j,*k,*l});
k++;
l--;
while (*k == *(k - 1) && *l == *(l + 1))
{
k++;
l--;
}
}
}
}
}
return result;
}
};