-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0703-KthLargestElementInAStream.cs
54 lines (46 loc) · 1.4 KB
/
0703-KthLargestElementInAStream.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//-----------------------------------------------------------------------------
// Runtime: 200ms
// Memory Usage: 40.4 MB
// Link: https://leetcode.com/submissions/detail/345114657/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _0703_KthLargestElementInAStream
{
private readonly IDictionary<int, int> minHeap;
private readonly int k;
private int size = 0;
public _0703_KthLargestElementInAStream(int k, int[] nums)
{
this.k = k;
minHeap = new SortedDictionary<int, int>();
foreach (var num in nums)
Add(num);
}
public int Add(int val)
{
if (minHeap.ContainsKey(val))
minHeap[val]++;
else
minHeap[val] = 1;
size++;
if (size > k)
{
var pair = minHeap.First();
if (pair.Value > 1)
minHeap[pair.Key]--;
else
minHeap.Remove(pair.Key);
size--;
}
return minHeap.Keys.First();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.Add(val);
*/
}