-
Notifications
You must be signed in to change notification settings - Fork 7
/
28. Maximum Frequency Stack
66 lines (63 loc) · 1.93 KB
/
28. Maximum Frequency Stack
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
66
//Using Stack
class FreqStack {
Map<Integer, Integer> freqMap;
Map<Integer, Stack<Integer>> freqStack;
int maxFreq;
public FreqStack() {
freqMap = new HashMap<>();
freqStack = new HashMap<>();
maxFreq = 0;
}
//Increment value in freqMap,
//updating the maxFreq
//Adding value in dfreqStack
public void push(int x) {
int freq = freqMap.getOrDefault(x,0)+1;
freqMap.put(x, freq);
if(freq > maxFreq) maxFreq = freq;
freqStack.computeIfAbsent(freq, f->new Stack()).push(x);
}
//Return and remove the top of maxFreq
//Update maxFreq (Decrementing, if applicable)
//Update freqMap
public int pop() {
Stack<Integer> s = freqStack.get(maxFreq);
int top = s.pop();
if(s.isEmpty()) maxFreq--;
freqMap.put(top, freqMap.get(top)-1);
return top;
}
}
//Using ArrayList
class FreqStack {
Map<Integer, Integer> freqMap;
ArrayList<ArrayList<Integer>> freqStack;
int maxFreq;
public FreqStack() {
freqMap = new HashMap<>();
freqStack = new ArrayList<>();
freqStack.add(new ArrayList<Integer>());
maxFreq = 0;
}
//Increment value in freqMap,
//updating the maxFreq
//Adding value in dfreqStack
public void push(int x) {
int freq = freqMap.getOrDefault(x,0)+1;
freqMap.put(x, freq);
if(freq > maxFreq) maxFreq = freq;
//freqStack.computeIfAbsent(freq, f->new Stack()).push(x);
if(freqStack.size() <= freq) freqStack.add(new ArrayList());
freqStack.get(freq).add(x);
}
//Return and remove the top of maxFreq
//Update maxFreq (Decrementing, if applicable)
//Update freqMap
public int pop() {
ArrayList<Integer> s = freqStack.get(maxFreq);
int top = s.remove(s.size()-1);
if(s.isEmpty()) maxFreq--;
freqMap.put(top, freqMap.get(top)-1);
return top;
}
}