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
|
int Partition(int* nums, int low, int high) { int pivot = nums[low]; while (low < high) { while (low < high && pivot <= nums[high]) --high; nums[low] = nums[high]; while (low < high && pivot >= nums[low]) low++; nums[high] = nums[low]; } nums[low] = pivot; return low; }
void QuickSort(int* nums, int low, int high) { if (low < high) { int pivotpos = Partition(nums, low, high); QuickSort(nums, low, pivotpos - 1); QuickSort(nums, pivotpos + 1, high); } }
int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes) { int** ans = malloc(200 * sizeof(int*)); int cnt = 0; QuickSort(nums, 0, numsSize - 1); for (int i = 0; i < numsSize; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; for (int j = i + 1; j < numsSize; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) continue; int left = j + 1, right = numsSize - 1; while (left < right) { long long sum = (long long) nums[i] + nums[j] + nums[left] + nums[right]; if (sum > target) --right; else if (sum < target) left++; else { ans[cnt] = malloc(4 * sizeof(int)); ans[cnt][0] = nums[i]; ans[cnt][1] = nums[j]; ans[cnt][2] = nums[left]; ans[cnt][3] = nums[right]; cnt++; while (left < right && nums[left] == nums[left + 1]) left++; while (left < right && nums[right] == nums[right - 1]) --right; left++; --right; } } } } *returnSize = cnt; *returnColumnSizes = malloc(cnt * sizeof(int)); for (int i = 0; i < cnt; i++) (*returnColumnSizes)[i] = 4; ans = realloc(ans, cnt * sizeof(int*)); return ans; }
|