1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
|
#include <stdio.h> #include <stdlib.h>
int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); }
int** threeSum(int* nums, int numsSize, int* returnSize) {
int **return_array = (int **)malloc(sizeof(int *) * numsSize * (numsSize-1));
qsort(nums, numsSize, sizeof(int), cmpfunc);
int *start, *end; int rerurn_size = 0; int temp = 0;
for (int i = 0; i < numsSize-2; ++i) { if (nums[i-1] == nums[i] && i > 0) continue;
printf("=======================================\n");
start = &nums[i+1]; end = &nums[numsSize-1];
while(start < end) { printf("%d %d %d %d \n", i, nums[i], *start, *end); temp = *start + *end + nums[i]; if(temp == 0) { return_array[rerurn_size] = (int *)malloc(sizeof(int) * 3); return_array[rerurn_size][0] = nums[i]; return_array[rerurn_size][1] = *start; return_array[rerurn_size][2] = *end;
rerurn_size++; while(*start == *(start+1)) { printf("+\n"); start++; } #if 1 while((*end == *(end+1)) && (end != &nums[numsSize-1])) #else while(*end == *(end+1)) #endif { printf("-\n"); end--; }
start++; end--; } else if (temp < 0) { start++; } else { end--; }
printf("%p, %p\n", start, end); } }
*returnSize = rerurn_size; printf("rerurn_size = %d\n", rerurn_size);
return return_array; }
int nums[] = {1, -4, -4, 2, 0, 0, -2, 3, 3, -3, -4};
int main(int argc, char const *argv[]) {
int numsSize = sizeof(nums)/sizeof(int);
int returnSize = 0; int **return_array = NULL;
return_array = threeSum(nums, numsSize, &returnSize);
printf("\n"); if(return_array == NULL) return 0;
for (int i = 0; i < returnSize; ++i) { for (int j = 0; j < 3; ++j) { printf("%d ", return_array[i][j]); }
printf("\n"); }
for (int i = 0; i < returnSize; ++i) { free(return_array[i]); }
return 0; }
|