原题目连接
1. 题目描述
给你一个包含 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
2.代码如下
1. C语言
int compare(void *a,void *b)
{
return *((int *)a) - *((int *)b);
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
int **ret = NULL;
int count = 0;
int *retcol = NULL;
(*returnSize) = count;
(*returnColumnSizes) = retcol;
if (!nums || numsSize <= 2)
{
return ret;
}
qsort(nums,numsSize,sizeof(int),(void *)compare);
ret = (int **)realloc(ret,sizeof(int *)*numsSize*numsSize);
retcol = (int *)realloc(retcol,sizeof(int)*numsSize*numsSize);
for (int i = 0; i < numsSize-2;++i)
{
if (nums[i] > 0)
{
break;
}
if (i > 0 && nums[i] == nums[i-1] )
{
continue;
}
int head = i+1;
int tail = numsSize-1;
while (head < tail)
{
int target = nums[head] + nums[tail] + nums[i];
if (target == 0)
{
#if 0
在内部逐步扩展指针数组,会导致超时!
ret = (int **)realloc(ret,sizeof(int *)*(count+1));
retcol = (int *)realloc(retcol,sizeof(int)*(count+1));
#endif
retcol[count] = 3;
ret[count] = (int *)malloc(sizeof(int)*3);
ret[count][0] = nums[i];
ret[count][1] = nums[head];
ret[count][2] = nums[tail];
++count;
while (head < tail && nums[head] == nums[head+1])
{
++head;
}
while (head < tail && nums[tail] == nums[tail - 1])
{
--tail;
}
++head;
--tail;
}
else if (target < 0)
{
++head;
}
else
{
--tail;
}
}
}
(*returnSize) = count;
(*returnColumnSizes) = retcol;
return ret;
}
2. c++
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
const int size = (int)nums.size();
vector<vector<int>> ret;
if (size < 3)
{
return ret;
}
sort(nums.begin(),nums.end());
for (int i = 0; i < size -2;++i)
{
if (nums[i] > 0)
{
break;
}
if (i > 0 && nums[i] == nums[i-1])
{
continue;
}
int head = i+1;
int tail = size-1;
while (head < tail)
{
int target = nums[i] + nums[head] + nums[tail];
if (target == 0)
{
ret.push_back({nums[i],nums[head],nums[tail]});
while (head < tail && nums[head] == nums[head+1])
{
++head;
}
while (head < tail && nums[tail] == nums[tail-1])
{
--tail;
}
++head;
--tail;
}
else if (target < 0)
{
++head;
}
else
{
--tail;
}
}
}
return ret;
}
};