-
Notifications
You must be signed in to change notification settings - Fork 1
/
069_Min Heap.cpp
101 lines (77 loc) · 1.77 KB
/
069_Min Heap.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Time Complexity -> O(n log(n))
// Space Complextiy -> O(n)
#include <bits/stdc++.h>
class heap
{
private:
vector<int> arr;
public:
heap()
{
}
void insert(int val)
{
arr.push_back(val);
int idx = arr.size()-1;
while(idx >= 0)
{
int par = (idx-1) >> 1;
if(arr[par] > arr[idx])
{
swap(arr[par], arr[idx]);
idx = par;
}
else
return;
}
}
int deleteFromHeap()
{
if(arr.empty())
return -1;
int ans = arr[0];
arr[0] = arr.back();
arr.pop_back();
int n = arr.size(), idx = 0;
while(idx < n)
{
int leftIdx = (2*idx) + 1;
int rightIdx = (2*idx) + 2;
if(leftIdx < n and arr[leftIdx] < arr[idx])
{
if (arr[leftIdx] < arr[rightIdx]) {
swap(arr[leftIdx], arr[idx]);
idx = leftIdx;
} else {
swap(arr[rightIdx], arr[idx]);
idx = rightIdx;
}
}
else if(rightIdx < n and arr[rightIdx] < arr[idx])
{
swap(arr[rightIdx], arr[idx]);
idx = rightIdx;
}
else
break;
}
return ans;
}
};
vector<int> minHeap(int n, vector<vector<int>>& q) {
// Write your code here.
vector<int> ans;
heap h;
for(auto itr : q)
{
if(itr[0] == 0)
{
h.insert(itr[1]);
} else {
int cur = h.deleteFromHeap();
if (cur != -1)
ans.push_back(cur);
}
}
return ans;
}