-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution703.cs
40 lines (34 loc) · 1018 Bytes
/
Solution703.cs
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
namespace LeetCode.Solutions;
public class Solution703
{
/// <summary>
/// 703. Kth Largest Element in a Stream - Easy
/// <a href="https://leetcode.com/problems/kth-largest-element-in-a-stream">See the problem</a>
/// </summary>
public class KthLargest
{
private PriorityQueue<int, int> minHeap = new();
private int k;
public KthLargest(int k, int[] nums)
{
this.k = k;
// Initialize the heap with the given scores
foreach (int num in nums)
{
Add(num);
}
}
public int Add(int val)
{
// Add the new score to the heap
minHeap.Enqueue(val, val);
// If the heap size exceeds k, remove the smallest element
if (minHeap.Count > k)
{
minHeap.Dequeue();
}
// The root of the heap is the kth largest element
return minHeap.Peek();
}
}
}