|
1 | 1 | #include <stdio.h>
|
2 | 2 | #include <stdlib.h>
|
3 | 3 |
|
4 |
| -static int compare(const void *a, const void *b) |
| 4 | +static inline void swap(int *a, int *b) |
5 | 5 | {
|
6 |
| - return *(int *) a - *(int *) b; |
| 6 | + int t = *a; |
| 7 | + *a = *b; |
| 8 | + *b = t; |
7 | 9 | }
|
8 | 10 |
|
9 |
| -int findKthLargest(int* nums, int numsSize, int k) { |
10 |
| - qsort(nums, numsSize, sizeof(int), compare); |
11 |
| - return nums[numsSize - k]; |
| 11 | +static int partition(int *nums, int lo, int hi) |
| 12 | +{ |
| 13 | + if (lo >= hi) { |
| 14 | + return hi; |
| 15 | + } |
| 16 | + |
| 17 | + int i = lo; |
| 18 | + int j = hi - 1; |
| 19 | + int pivot = nums[hi]; |
| 20 | + while (i <= j) { |
| 21 | + while (i <= j && nums[i] <= pivot) { i++; } |
| 22 | + while (i <= j && nums[j] > pivot) { j--; } |
| 23 | + if (i < j) { |
| 24 | + swap(nums + i, nums + j); |
| 25 | + } |
| 26 | + } |
| 27 | + /* Loop invariant: j + 1 == i && nums[j] <= pivot && nums[i] > pivot |
| 28 | + * Besides, j could be -1 or i could be hi, so we swap [i] and [hi] |
| 29 | + */ |
| 30 | + swap(nums + i, nums + hi); |
| 31 | + return i; |
| 32 | +} |
| 33 | + |
| 34 | +int findKthLargest(int* nums, int numsSize, int k) |
| 35 | +{ |
| 36 | + int lo = 0, hi = numsSize - 1; |
| 37 | + for (; ;) { |
| 38 | + printf("A:%d %d\n", lo, hi); |
| 39 | + int p = partition(nums, lo, hi); |
| 40 | + printf("B:%d %d\n", p, numsSize - k); |
| 41 | + if (p < numsSize - k) { |
| 42 | + lo = p + 1; |
| 43 | + } else if (p > numsSize - k) { |
| 44 | + hi = p - 1; |
| 45 | + } else { |
| 46 | + lo = p; |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | + return nums[lo]; |
12 | 51 | }
|
13 | 52 |
|
14 | 53 |
|
|
0 commit comments