链接:https://leetcode-cn.com/problems/3sum
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
int CompareByIncrease(const void* a, const void* b)
{
return *(int*)a - *(int*)b; // 快排构造递增序列
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
*returnSize = 0;
if( numsSize < 3 )
{
return NULL;
}
int cur = 0;
int low = cur + 1;
int high = numsSize - 1;
int** returnArray = (int**)malloc(sizeof(int*) * (numsSize)*(numsSize));
*returnColumnSizes = (int*)malloc(sizeof(int) * (numsSize)*(numsSize));
qsort(nums, numsSize, sizeof(int), CompareByIncrease);
while((nums[cur] <= 0) && (cur + 1 < numsSize - 1))
{
low = cur + 1;
high = numsSize - 1;
while(low < high)
{
if(0 == (nums[low] + nums[high] + nums[cur]))
{
returnArray[*returnSize] = (int*)malloc(sizeof(int) * 3); // 每次找到一组,二级指针就分配三个空间
(*returnColumnSizes)[*returnSize] = 3; // 记录列数,非常骚而吊诡的操作
returnArray[*returnSize][0] = nums[cur];
returnArray[*returnSize][1] = nums[low];
returnArray[*returnSize][2] = nums[high];
(*returnSize)++;
// 去low和high的重,非常不规范的写法,但看着极端舒服
while( (nums[low] == nums[++low]) && (low < high) ); // 往后去重
while( (nums[high] == nums[--high]) && (low < high) ); // 往前去重
}
else if(0 < (nums[low] + nums[high] + nums[cur]))
{
high--;
}
else
{
low++;
}
}
while( (nums[cur] == nums[++cur]) && (cur + 1 < numsSize - 1) );
}
return returnArray;
}