该题与三数之和相同。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();
if (n < 3) return res;
sort(nums.begin(), nums.end()); //排序
for (int i = 0; i < n; ++ i)
{
if (nums[i] > 0) return res; //若第一个数大于0,加后面俩数就不可能小于0了
if (i > 0 && nums[i] == nums[i - 1]) continue; //跳过相同的数
int left = i + 1, right = n - 1; //第2,3个数采用双指针,一前一后
while (left < right)
{
int curSum = nums[i] + nums[left] + nums[right];
if (curSum == 0)
{
res.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left + 1]) ++ left;
while (left < right && nums[right] == nums[right - 1]) -- right;
++ left, -- right;
}
else if (curSum > 0) -- right; //结果大于0,右指针往左移
else ++ left; //结果小于0,左指针往右移
}
}
return res;
}
};