# 算法15. 三数之和_(c语言版)

## 1. 题目描述

``````给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？请你找出所有满足条件且不重复的三元组。

[
[-1, 0, 1],
[-1, -1, 2]
]
``````

## 3. 解法1_双指针法

``````/*
author: xidoublestar
date: 2020-5-21
*/
int compare(const void* a, const void* b)
{
return (*(int*)a - *(int*)b);
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
//排除平台只输出]的bug
*returnSize = 0;
//排除输入小于3的情况
if (numsSize < 3)
return NULL;
//使用qsort函数快速排序
qsort(nums, numsSize, sizeof(int), compare);
//申请二级指针空间
int** returnArray = (int**)malloc(sizeof(int*) * (numsSize - 2) * (numsSize - 2));
//申请每个一维数组大小的空间
*returnColumnSizes = (int*)malloc(sizeof(int) * (numsSize - 2) * (numsSize - 2));
int cur = 0, low = 0,high = 0;
//cur遍历数组，low和high分别做为左值和右值的下标往中间夹
while (nums[cur] <= 0 && cur < numsSize - 2) {
low = cur + 1;
high = numsSize - 1;
while (low < high) {
if (0 == (nums[cur] + nums[low] + nums[high])) {
returnArray[*returnSize] = (int*)malloc(sizeof(int) * 3);//每找到一组，二级指针分配3个空间
(*returnColumnSizes)[*returnSize] = 3;//记录列数
returnArray[*returnSize][0] = nums[cur];
returnArray[*returnSize][1] = nums[low];
returnArray[(*returnSize)++][2] = nums[high];
while ((nums[low] == nums[++low]) && (low < high));//往后去重
while ((nums[high] == nums[--high]) && (low < high));//往前去重
}
else if (0 < (nums[cur] + nums[low] + nums[high])) {
high--;
}
else {
low++;
}
}
while ((nums[cur] == nums[++cur]) && (cur < numsSize - 2));//cur左值去重
}
return returnArray;
}
``````

• 博文量
91
• 访问量
94252