Skip to content

Commit 351fda9

Browse files
authoredSep 3, 2019
Add files via upload
1 parent b356b95 commit 351fda9

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
 
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Runtime: 52 ms, faster than 52.57% of C++ online submissions for Kth Largest Element in a Stream.
2+
// Memory Usage: 19.5 MB, less than 65.00% of C++ online submissions for Kth Largest Element in a Stream.
3+
4+
class KthLargest
5+
{
6+
public:
7+
KthLargest(int k, vector<int>& nums)
8+
{
9+
size = k;
10+
for (int i = 0; i < k && i < nums.size(); ++i)
11+
minHeap.push_back(nums[i]);
12+
13+
make_heap(minHeap.begin(), minHeap.end(), comp);
14+
15+
for (int i = k; i < nums.size(); ++i)
16+
{
17+
if (nums[i] > minHeap[0])
18+
{
19+
pop_heap(minHeap.begin(), minHeap.end(), comp);
20+
minHeap.pop_back();
21+
22+
minHeap.push_back(nums[i]);
23+
push_heap(minHeap.begin(), minHeap.end(), comp);
24+
}
25+
}
26+
}
27+
28+
int add(int val)
29+
{
30+
if (size != minHeap.size())
31+
{
32+
minHeap.push_back(val);
33+
push_heap(minHeap.begin(), minHeap.end(), comp);
34+
}
35+
else
36+
{
37+
if (val > minHeap[0])
38+
{
39+
pop_heap(minHeap.begin(), minHeap.end(), comp);
40+
minHeap.pop_back();
41+
42+
minHeap.push_back(val);
43+
push_heap(minHeap.begin(), minHeap.end(), comp);
44+
}
45+
}
46+
return minHeap[0];
47+
}
48+
private:
49+
int size;
50+
vector<int> minHeap;
51+
bool (*comp)(const int&, const int&) = [](const int& num1, const int& num2){return num1 > num2;};
52+
};
53+
54+
/**
55+
* Your KthLargest object will be instantiated and called as such:
56+
* KthLargest* obj = new KthLargest(k, nums);
57+
* int param_1 = obj->add(val);
58+
*/

0 commit comments

Comments
 (0)
Please sign in to comment.