-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
65 lines (62 loc) · 1.15 KB
/
Program.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
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Linq;
namespace MaximumFrequencyStack
{
class Program
{
static void Main(string[] args)
{
var stack = new FreqStack();
stack.Push(4);
stack.Push(0);
stack.Push(9);
stack.Push(3);
stack.Push(4);
stack.Push(2);
stack.Pop();
stack.Push(6);
stack.Pop();
stack.Push(1);
stack.Pop();
stack.Push(1);
stack.Pop();
stack.Push(4);
stack.Pop();
stack.Pop();
stack.Pop();
stack.Pop();
stack.Pop();
stack.Pop();
}
}
public class FreqStack
{
private Dictionary<int, int> freq;
private Dictionary<int, Stack<int>> groups;
private int maxFreq;
public FreqStack()
{
freq = new Dictionary<int, int>();
groups = new Dictionary<int, Stack<int>>();
}
public void Push(int x)
{
if (!freq.ContainsKey(x))
freq[x] = 0;
freq[x]++;
maxFreq = Math.Max(maxFreq, freq[x]);
if (!groups.ContainsKey(freq[x]))
groups[freq[x]] = new Stack<int>();
groups[freq[x]].Push(x);
}
public int Pop()
{
int res = groups[maxFreq].Pop();
if (groups[maxFreq].Count == 0)
maxFreq--;
freq[res]--;
return res;
}
}
}