# 三数之和
给你一个包含 n
个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0
且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
以下程序实现了这一功能,请你填补空白处内容:
```cpp
#include
#include
class Solution
{
public:
vector> threeSum(vector &nums)
{
vector> r;
if (nums.size() == 0)
return r;
sort(nums.begin(), nums.end());
int cur, left, right;
cur = 0;
while (cur < nums.size())
{
if (nums[cur] > 0)
break;
left = cur + 1;
right = nums.size() - 1;
while (left < right)
{
int n = nums[cur] + nums[left] + nums[right];
if (n == 0)
{
r.emplace_back(vector({nums[cur], nums[left], nums[right]}));
int t = left + 1;
__________________________;
}
else if (n > 0)
{
int t = right - 1;
while (t > left && nums[t] == nums[right])
t--;
right = t;
}
else
{
int t = left + 1;
while (t < right && nums[t] == nums[left])
t++;
left = t;
}
}
int t = cur + 1;
while (t < nums.size() && nums[t] == nums[cur])
t++;
cur = t;
}
return r;
}
};
```
## template
```cpp
#include
#include
class Solution
{
public:
vector> threeSum(vector &nums)
{
vector> r;
if (nums.size() == 0)
return r;
sort(nums.begin(), nums.end());
int cur, left, right;
cur = 0;
while (cur < nums.size())
{
if (nums[cur] > 0)
break;
left = cur + 1;
right = nums.size() - 1;
while (left < right)
{
int n = nums[cur] + nums[left] + nums[right];
if (n == 0)
{
r.emplace_back(vector({nums[cur], nums[left], nums[right]}));
int t = left + 1;
while (t < right && nums[t] == nums[left])
t++;
left = t;
t = right - 1;
while (t > left && nums[t] == nums[right])
t--;
right = t;
}
else if (n > 0)
{
int t = right - 1;
while (t > left && nums[t] == nums[right])
t--;
right = t;
}
else
{
int t = left + 1;
while (t < right && nums[t] == nums[left])
t++;
left = t;
}
}
int t = cur + 1;
while (t < nums.size() && nums[t] == nums[cur])
t++;
cur = t;
}
return r;
}
};
```
## 答案
```cpp
while (t < right && nums[t] == nums[left])
t++;
left = t;
t = right - 1;
while (t > left && nums[t] == nums[right])
t--;
right = t;
```
## 选项
### A
```cpp
while (t < right)
t++;
left = t;
t = right - 1;
while (t > left)
t--;
right = t;
```
### B
```cpp
while (t < right)
t++;
left = t;
t = right + 1;
while (t > left)
t--;
right = t;
```
### C
```cpp
while (t < right && nums[t] == nums[left])
t++;
left = t;
t = right + 1;
while (t > left && nums[t] == nums[right])
t--;
right = t;
```