Movatterモバイル変換


[0]ホーム

URL:


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

Commit502d663

Browse files
Add max heap approach for No.215
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parentd4f6d7e commit502d663

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
staticinlinevoidswap(int*a,int*b)
56
{
67
intt=*a;
78
*a=*b;
89
*b=t;
910
}
1011

12+
staticvoidmax_heapify(int*nums,intsize,intparent)
13+
{
14+
inti=parent;/* parent is the root */
15+
intl=parent*2+1;
16+
intr=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+
staticvoidbuild_max_heap(int*nums,intsize)
34+
{
35+
inti;
36+
for (i=size /2;i >=0;i--) {
37+
max_heapify(nums,size,i);
38+
}
39+
}
40+
1141
staticintquick_select(int*nums,intlo,inthi,intk)
1242
{
1343
if (lo >=hi) {
@@ -40,8 +70,22 @@ static int quick_select(int *nums, int lo, int hi, int k)
4070

4171
intfindKthLargest(int*nums,intnumsSize,intk)
4272
{
73+
#if0
4374
inti=quick_select(nums,0,numsSize-1,k);
4475
returnnums[i];
76+
#else
77+
inti;
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+
returnnums[0];
88+
#endif
4589
}
4690

4791

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp