Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 502d663

Browse files
Add max heap approach for No.215
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent d4f6d7e commit 502d663

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎0215_kth_largest_element_in_an_array/kth_elem.c‎

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

4+
45
static inline void swap(int *a, int *b)
56
{
67
int t = *a;
78
*a = *b;
89
*b = t;
910
}
1011

12+
static void max_heapify(int *nums, int size, int parent)
13+
{
14+
int i = parent; /* parent is the root */
15+
int l = parent * 2 + 1;
16+
int r = parent * 2 + 2;
17+
18+
if (l < size && nums[l] > nums[i]) {
19+
i = l;
20+
}
21+
22+
if (r < size && nums[r] > nums[i]) {
23+
i = r;
24+
}
25+
26+
/* percolate up */
27+
if (i != parent) {
28+
swap(&nums[i], &nums[parent]);
29+
max_heapify(nums, size, i);
30+
}
31+
}
32+
33+
static void build_max_heap(int *nums, int size)
34+
{
35+
int i;
36+
for (i = size / 2; i >= 0; i--) {
37+
max_heapify(nums, size, i);
38+
}
39+
}
40+
1141
static int quick_select(int *nums, int lo, int hi, int k)
1242
{
1343
if (lo >= hi) {
@@ -40,8 +70,22 @@ static int quick_select(int *nums, int lo, int hi, int k)
4070

4171
int findKthLargest(int* nums, int numsSize, int k)
4272
{
73+
#if 0
4374
int i = quick_select(nums, 0, numsSize - 1, k);
4475
return nums[i];
76+
#else
77+
int i;
78+
79+
build_max_heap(nums, numsSize);
80+
81+
/* nums[0] is the largest element and the last is the least */
82+
for (i = numsSize - 1; i >= numsSize - k + 1; i--) {
83+
swap(&nums[0], &nums[i]);
84+
max_heapify(nums, numsSize, 0);
85+
}
86+
87+
return nums[0];
88+
#endif
4589
}
4690

4791

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /