-
Notifications
You must be signed in to change notification settings - Fork 0
/
215.kth-largest-element-in-an-array.cpp
62 lines (56 loc) · 1.26 KB
/
215.kth-largest-element-in-an-array.cpp
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
/*
* @lc app=leetcode id=215 lang=cpp
*
* [215] Kth Largest Element in an Array
*/
#define LEFT(x) (x*2+1)
#define RIGHT(x) (x*2+2)
class Solution {
public:
vector<int> heap;
int size;
void heapify(int l)
{
if (LEFT(l) >= size)
return;
if (LEFT(l) < size && RIGHT(l) == size)
{
if (heap[LEFT(l)] > heap[l])
swap(heap[LEFT(l)], heap[l]);
return;
}
if (heap[LEFT(l)] > heap[RIGHT(l)])
{
if (heap[l] < heap[LEFT(l)])
{
swap(heap[l], heap[LEFT(l)]);
heapify(LEFT(l));
}
}
else
{
if (heap[l] < heap[RIGHT(l)])
{
swap(heap[l], heap[RIGHT(l)]);
heapify(RIGHT(l));
}
}
}
void build_heap()
{
for (int i = size/2;i >=0; --i)
heapify(i);
}
int findKthLargest(vector<int>& nums, int k) {
heap = nums;
size = nums.size();
build_heap();
for(int i = 0;i < k-1;i++)
{
swap(heap[0], heap[size-1]);
size--;
heapify(0);
}
return heap[0];
}
};