# LeetCode 15. 三数之和 3Sum（C语言）

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

## 题目解答：

#### 方法1：排序法

/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int comp(void* a, void* b) {
return *(int*)a > *(int*)b ? 1 : -1;
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
int n = numsSize;
qsort(nums, n, sizeof(int), comp);
if(n < 3 || nums[0] > 0 || nums[0] + nums[1] + nums[2] > 0)
return NULL;
int** result = NULL;
int i = 0, size = 0;
int left = 0, right = 0;
for(i = 0; i < n - 2 && nums[i] <= 0; i++) {
left = i + 1;
right = n - 1;
while(left < right) {
if(nums[i] + nums[left] + nums[right] > 0)
right--;
else if(nums[i] + nums[left] + nums[right] < 0)
left++;
else {
size++;
result = (int**)realloc(result, size * sizeof(int*));
result[size - 1] = (int*)malloc(3 * sizeof(int));
result[size - 1][0] = nums[i];
result[size - 1][1] = nums[left];
result[size - 1][2] = nums[right];
while(left + 1 < n && nums[left] == nums[left + 1])
left++;
while(right - 1 >= 0 && nums[right] == nums[right - 1])
right--;
left++;
right--;
}
}
while(i + 1 < n && nums[i] == nums[i + 1])
i++;
}
*returnSize = size;
return result;
}


#### 方法2： Hash+排序

1. target <= max && hash[target] && nums[j] < target (最后一个条件保证存储的结果都是递增的，避免重复结果)
2. target == nums[j] && flag (flag表示nums[j]之前是否有与其相等的数字，有则为真，无则为假)

/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int comp(void* a, void* b) {
return *(int*)a > *(int*)b ? 1 : -1;
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
int n = numsSize;
int i = 0, j = 0, size = 0, t = 0;
qsort(nums, n, sizeof(int), comp);
if(n < 3 || nums[0] > 0 || nums[n - 1] < 0 || nums[0] + nums[1] + nums[2] > 0)
return NULL;
bool* hash = (bool*)calloc(nums[n - 1] + 1, sizeof(bool));
for(i = 0; i < n; i++) {
if(nums[i] >= 0)
hash[nums[i]] = true;
}
int** result = NULL;
for(i = 0; i < n - 2 && nums[i] <= 0; i++) {
for(j = i + 1; j < n - 1; j++) {
bool flag = false;
while(nums[j] == nums[j + 1]) {
j++;
flag = true;
}
t = nums[i] + nums[j];
if(t > 0)
break;
if((-t <= nums[n - 1] && hash[-t] && nums[j] < -t) || (-t == nums[j] && flag)) {
size++;
result = (int**)realloc(result, size * sizeof(int*));
result[size - 1] = (int*)malloc(3 * sizeof(int));
result[size - 1][0] = nums[i];
result[size - 1][1] = nums[j];
result[size - 1][2] = -t;
}
}
while(nums[i] == nums[i + 1])
i++;
}
*returnSize = size;
return result;
}