题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
/** * * @param num int整型一维数组 * @param numLen int num数组长度 * @return int整型二维数组 * @return int* returnSize 返回数组行数 * @return int** returnColumnSizes 返回数组列数 */ #include <malloc.h> #include <math.h> #include <stdio.h> #include <stdlib.h> void BubbleSort(int *num, int numLen) { while (numLen > 0) { for (int i = 0; i < numLen - 1; i++) { if (num[i] > num[i + 1]) { int temp = num[i + 1]; num[i + 1] = num[i]; num[i] = temp; } } numLen--; } } int** threeSum(int* num, int numLen, int* returnSize, int** returnColumnSizes ) { int **ret = NULL; int columnSizes = 0; int flag = 0; BubbleSort(num, numLen); for (int i = 0; i < numLen - 2; i++) { for (int j = i + 1; j < numLen - 1; j++) { for (int k = j + 1; k < numLen; k++) { if (num[i] + num[j] + num[k] == 0) { if (columnSizes > 0) { for (int nn = 0; nn < columnSizes; nn++) { if ((num[i] == ret[nn][0]) && (num[j] == ret[nn][1]) && (num[k] == ret[nn][2])) { flag = 1; break;; } } if (flag == 1) { flag = 0; continue; } } columnSizes++; ret = (int **)realloc(ret, sizeof(int *) * columnSizes); ret[columnSizes - 1] = (int *)malloc(sizeof(int) * columnSizes); ret[columnSizes - 1][0] = num[i]; ret[columnSizes - 1][1] = num[j]; ret[columnSizes - 1][2] = num[k]; } } } }; *returnColumnSizes = (int *)malloc(columnSizes * sizeof(int)); *returnSize = columnSizes; for (int i = 0; i < columnSizes; i++) { (*returnColumnSizes)[i] = 3; } return ret; }