javascript
复制代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> vecNum;
sort(nums.begin(), nums.end());
if (nums[0] > 0 || nums.size() < 3)
{
return vecNum;
}
int i = 0;
int k = 0;
int j = 0;
for (int nIndex = 0; nIndex < nums.size() - 2; nIndex++)
{
if (nIndex != 0)
{
// 索引i的去重处理
if (nums[i] == nums[nIndex])
{
continue;
}
}
i = nIndex;
k = nIndex + 1;
j = nums.size() - 1;
if (nums[i] <= 0)
{
while (i != j && j != k && i != j && k < j)
{
int num = nums[i] + nums[k] + nums[j];
if (num > 0)
{
j--;
}
else if (num < 0)
{
k++;
}
else
{
// 只有只和等于0的时候才进行去重处理
vecNum.push_back({ nums[i], nums[k], nums[j] });
// 索引j的去重处理
while (1)
{
j--;
if (j <= k || nums[j] != nums[j + 1])
{
break;
}
}
// 索引k的去重处理
while (1)
{
k++;
if (k >= j || nums[k] != nums[k - 1] )
{
break;
}
}
}
}
}
}
return vecNum;
}
};