|
| 1 | +int compareInt(const void *a, const void *b) { |
| 2 | + return *(int*)a - *(int*)b; |
| 3 | +} |
| 4 | + |
| 5 | +/** |
| 6 | + * Return an array of arrays of size *returnSize. |
| 7 | + * The sizes of the arrays are returned as *returnColumnSizes array. |
| 8 | + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). |
| 9 | + */ |
| 10 | +int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { |
| 11 | + int cap = 32; |
| 12 | + int **result = (int**)malloc(sizeof(int*) * cap); |
| 13 | + int *cols = (int*)malloc(sizeof(int) * cap); |
| 14 | + int *triplet; |
| 15 | + int sum, target, count; |
| 16 | + int i, left, right; |
| 17 | + |
| 18 | + qsort(nums, numsSize, sizeof(int), compareInt); |
| 19 | + |
| 20 | + count = 0; |
| 21 | + for (i = 0; i < numsSize - 2; i++) { |
| 22 | + // The array is sorted, there is no possible tripet when this happen. |
| 23 | + if (nums[i] > 0) { |
| 24 | + break; |
| 25 | + } |
| 26 | + // skip element with same value to avoid duplicate triplets. |
| 27 | + if (i > 0 && nums[i] == nums[i - 1]) { |
| 28 | + continue; |
| 29 | + } |
| 30 | + target = 0 - nums[i]; |
| 31 | + left = i + 1; |
| 32 | + right = numsSize - 1; |
| 33 | + while (left < right) { |
| 34 | + sum = nums[left] + nums[right]; |
| 35 | + if (sum > target) { |
| 36 | + right--; |
| 37 | + } else if (sum < target) { |
| 38 | + left++; |
| 39 | + } else { |
| 40 | + triplet = (int*)malloc(sizeof(int) * 3); |
| 41 | + triplet[0] = nums[i]; |
| 42 | + triplet[1] = nums[left]; |
| 43 | + triplet[2] = nums[right]; |
| 44 | + |
| 45 | + result[count] = triplet; |
| 46 | + cols[count] = 3; |
| 47 | + count++; |
| 48 | + |
| 49 | + if (count == cap) { |
| 50 | + cap *= 2; |
| 51 | + result = (int**)realloc(result, sizeof(int*) * cap); |
| 52 | + cols = (int*)realloc(cols, sizeof(int) * cap); |
| 53 | + } |
| 54 | + |
| 55 | + left++; |
| 56 | + right--; |
| 57 | + |
| 58 | + // skip element with same value to avoid duplicate triplets. |
| 59 | + while(left < right && nums[left] == nums[left - 1]) { |
| 60 | + left++; |
| 61 | + } |
| 62 | + while(left < right && nums[right] == nums[right + 1]) { |
| 63 | + right--; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + *returnSize = count; |
| 69 | + *returnColumnSizes = cols; |
| 70 | + |
| 71 | + return result; |
| 72 | +} |
0 commit comments