Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
C++
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
std::sort(nums.begin(),nums.end());
for(int k = 0;k < nums.size();++k)
{
if(nums[k] > 0)break;
if(k > 0&&nums[k] == nums[k - 1])continue;
int i = k + 1,j = nums.size() - 1;
while(i < j)
{
if(nums[k] + nums[i] + nums[j] == 0)
{
res.push_back({nums[k],nums[i],nums[j]});
while(i < j&&nums[i] == nums[i + 1])++i;
while(i < j&&nums[j] == nums[j - 1])--j;
++i;
--j;
}
else if(nums[k] + nums[i] + nums[j] > 0)
--j;
else
++i;
}
}
return res;
}
本文探讨了如何在一个整数数组中寻找三个元素,使它们的和等于零,并提供了一个有效的C++解决方案。该算法首先对数组进行排序,然后使用双指针技术遍历数组以找到所有不重复的三元组。
752

被折叠的 条评论
为什么被折叠?



