有一个包含n个整数的数组nums,判断nums中是否存在三个元素a、b、 c,使得 a + b + c = 0,请你找出所有满足条件且不重复的三元组。C语言
时间: 2023-10-25 20:14:23 浏览: 250
以下是一个C语言的解法,利用双指针的思想:
```
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
qsort(nums, numsSize, sizeof(int), cmp); // 先对数组进行排序
int count = 0;
int **result = (int**)malloc(sizeof(int*) * numsSize * numsSize);
*returnColumnSizes = (int*)malloc(sizeof(int) * numsSize * numsSize);
for (int i = 0; i < numsSize; i++) {
if (i > 0 && nums[i] == nums[i - 1]) { // 如果当前数字与前一个数字相同,则跳过
continue;
}
int left = i + 1;
int right = numsSize - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result[count] = (int*)malloc(sizeof(int) * 3);
result[count][0] = nums[i];
result[count][1] = nums[left];
result[count][2] = nums[right];
(*returnColumnSizes)[count] = 3;
count++;
while (left < right && nums[left] == nums[left + 1]) { // 如果当前数字与下一个数字相同,则跳过
left++;
}
while (left < right && nums[right] == nums[right - 1]) { // 如果当前数字与前一个数字相同,则跳过
right--;
}
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
*returnSize = count;
return result;
}
```
在主函数中,我们可以这样调用它:
```
int main() {
int nums[] = {-1, 0, 1, 2, -1, -4};
int numsSize = 6;
int returnSize = 0;
int *returnColumnSizes = NULL;
int **result = threeSum(nums, numsSize, &returnSize, &returnColumnSizes);
for (int i = 0; i < returnSize; i++) {
for (int j = 0; j < returnColumnSizes[i]; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果为:
```
-1 -1 2
-1 0 1
```
阅读全文