-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth-largest-element-in-an-array.c
More file actions
64 lines (50 loc) · 1.3 KB
/
kth-largest-element-in-an-array.c
File metadata and controls
64 lines (50 loc) · 1.3 KB
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
62
63
64
int pop(int* heap, int* size){
int idx = 0;
int ret = heap[idx];
heap[idx] = heap[--(*size)];
while(1){
int smallest = idx;
int left = idx * 2 + 1;
int right = idx * 2 + 2;
if(left < *size && heap[left] < heap[smallest])
smallest = left;
if(right < *size && heap[right] < heap[smallest])
smallest = right;
if(smallest != idx){
int tmp = heap[idx];
heap[idx] = heap[smallest];
heap[smallest] = tmp;
idx = smallest;
}else
break;
}
return ret;
}
void push(int* heap, int* size, int capacity, int val){
if(*size == capacity){
if(heap[0] < val)
pop(heap, size);
else
return;
}
int idx = (*size)++;
heap[idx] = val;
while(idx > 0){
int parent = (idx - 1) / 2;
if(heap[parent] > heap[idx]){
int tmp = heap[idx];
heap[idx] = heap[parent];
heap[parent] = tmp;
idx = parent;
}else
break;
}
}
int findKthLargest(int* nums, int numsSize, int k) {
int heap[k];
int h_len = 0;
int ret;
for(int i = 0; i < numsSize; i++)
push(heap, &h_len, k, nums[i]);
return pop(heap, &h_len);
}