Skip to content

Commit

Permalink
Used priority queue.
Browse files Browse the repository at this point in the history
  • Loading branch information
orhtej2 committed Sep 3, 2024
1 parent 92de8fa commit 992a501
Showing 1 changed file with 8 additions and 14 deletions.
22 changes: 8 additions & 14 deletions kth-largest-element-in-a-stream/solution.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

#include <cassert>

#include <iterator>
#include <algorithm>
#include <vector>
#include <set>
#include <queue>

class KthLargest {
std::multiset<int, std::greater<int>> scores;
std::priority_queue<int, std::vector<int>, std::greater<int>> scores;
const int k;
public:
KthLargest(int k, const std::vector<int>& nums) : k(k) {
Expand All @@ -18,16 +18,10 @@ class KthLargest {
}

int add(int val) {
if (scores.size() < static_cast<size_t>(k)) {
scores.insert(val);
}
else {
auto it = scores.lower_bound(val);
if (it != scores.end()) {
scores.insert(val);
scores.erase(std::prev(scores.end()));
}
}
return *(scores.rbegin());
scores.push(val);
if (scores.size() > static_cast<size_t>(k))
scores.pop();

return scores.top();
}
};

0 comments on commit 992a501

Please sign in to comment.