aboutsummaryrefslogtreecommitdiff
path: root/kth_largest_element_stream.cpp
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /kth_largest_element_stream.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'kth_largest_element_stream.cpp')
-rw-r--r--kth_largest_element_stream.cpp40
1 files changed, 40 insertions, 0 deletions
diff --git a/kth_largest_element_stream.cpp b/kth_largest_element_stream.cpp
new file mode 100644
index 0000000..805d144
--- /dev/null
+++ b/kth_largest_element_stream.cpp
@@ -0,0 +1,40 @@
+// 703. Kth Largest Element in a Stream
+#include "leetcode.h"
+
+/*
+ * design a class to find the k'th largest element in a stream. note that it is
+ * the k'th largest element in the sorted order, not the k'th distinct element.
+ * implement 'KthLargest' class:
+ * - KthLargest(int k, int[] nums) initialises the objct with the integer 'k'
+ * and the stream of integers 'nums' int add(int val) appends the integer 'val'
+ * to the stream and returns the element representing the k'th largest stream
+ * element
+ */
+
+class KthLargest {
+ priority_queue<int, vector<int>, greater<int>> pq;
+ int size;
+
+public:
+ KthLargest(int k, vector<int> &nums) {
+ size = k;
+ for (int i = 0; i < nums.size(); i++) {
+ pq.push(nums[i]);
+ if (pq.size() > k)
+ pq.pop();
+ }
+ }
+ int add(int val) {
+ pq.push(val);
+ if (pq.size() > size)
+ pq.pop();
+ return pq.top();
+ }
+};
+
+int main() {
+ int k, val;
+ vector<int> nums;
+ KthLargest *obj = new KthLargest(k, nums);
+ int param_1 = obj->add(val);
+}