/**
* 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 Cmp(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;
}
qsort(nums, numsSize, sizeof(int), Cmp);
int k, i, j, sum;
int **res = (int **)malloc(sizeof(int *) * 20000);
*returnColumnSizes = (int *)malloc(sizeof(int) * 20000);
for (k = 0; k < numsSize - 2; k++) {
if (nums[k] > 0) {
return res;
}
if (k > 0 && nums[k] == nums[k - 1]) {
continue;
}
i = k + 1;
j = numsSize - 1;
while (i < j) {
sum = nums[k] + nums[i] + nums[j];
if (sum == 0) {
// printf("k:%d, i:%d, j:%d, *returnSize:%d
", k, i, j, *returnSize);
res[*returnSize] = (int *)malloc(sizeof(int) * 3);
(*returnColumnSizes)[*returnSize] = 3;
res[*returnSize][0] = nums[k];
res[*returnSize][1] = nums[i];
res[*returnSize][2] = nums[j];
*returnSize += 1;
// printf("1 i:%d, j:%d
", i, j);
// 更新和去重
while(i < j && nums[i] == nums[++i]) {
}
// printf("2 i:%d, j:%d
", i, j);
// 更新和去重
while(i < j && nums[j] == nums[--j]) {
}
// printf("3 i:%d, j:%d
", i, j);
} else if (sum < 0) {
i++;
} else {
j--;
}
}
}
return res;
}
int Cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int threeSumClosest(int* nums, int numsSize, int target)
{
// 排序
qsort(nums, numsSize, sizeof(int), Cmp);
int k, i, j, sum, best, sub;
best = 1e7; // 用一个很大的数,保证一定会更新1次best
for (k = 0; k < numsSize - 2; k++) {
if (k > 0 && nums[k] == nums[k - 1]) {
continue;
}
i = k + 1;
j = numsSize - 1;
while (i < j) {
sum = nums[k] + nums[i] + nums[j];
if (sum == target) {
return sum;
}
if (abs(sum - target) < abs(best - target)) {
best = sum;
}
if (sum < target) {
i++;
if (i == j) {
break;
}
} else if (sum > target) {
j--;
if (i == j) {
break;
}
}
}
}
return best;
}