Skip to content

Commit e9af039

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 84b500e commit e9af039

File tree

1 file changed

+44
-5
lines changed

1 file changed

+44
-5
lines changed

215_kth_largest_element_in_an_array/kth_elem.c

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,53 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4-
static int compare(const void *a, const void *b)
4+
static inline void swap(int *a, int *b)
55
{
6-
return *(int *) a - *(int *) b;
6+
int t = *a;
7+
*a = *b;
8+
*b = t;
79
}
810

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];
1251
}
1352

1453

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy