1
+ package hard
2
+
3
+ import HashTableTopic
4
+ import StackTopic
5
+ import java.util.*
6
+
7
+
8
+ /* *
9
+ * 895. Maximum Frequency Stack
10
+ * https://leetcode.com/problems/maximum-frequency-stack/
11
+ *
12
+ Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
13
+ Implement the FreqStack class:
14
+ FreqStack() constructs an empty frequency stack.
15
+ void push(int val) pushes an integer val onto the top of the stack.
16
+ int pop() removes and returns the most frequent element in the stack.
17
+ If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
18
+ BULLSHIT
19
+ */
20
+
21
+ class Hard895 : HashTableTopic , StackTopic {
22
+
23
+ class FreqStack {
24
+ var freq: MutableMap <Int , Int > = HashMap ()
25
+ var group: MutableMap <Int , Stack <Int >> = HashMap ()
26
+ var maxfreq: Int = 0
27
+
28
+ fun push (x : Int ) {
29
+ val f = freq.getOrDefault(x, 0 ) + 1
30
+ freq[x] = f
31
+ if (f > maxfreq) maxfreq = f
32
+ group.computeIfAbsent(f) { z: Int -> Stack <Int >() }.push(x)
33
+ }
34
+
35
+ fun pop (): Int {
36
+ val x = group[maxfreq]!! .pop()
37
+ freq[x] = freq[x]!! - 1
38
+ if (group[maxfreq]!! .size == 0 ) maxfreq--
39
+ return x
40
+ }
41
+ }
42
+ }
43
+
44
+ fun main () {
45
+ val stack = Hard895 .FreqStack ()
46
+ stack.push(5 )
47
+ stack.push(7 )
48
+ stack.push(5 )
49
+ stack.push(7 )
50
+ stack.push(4 )
51
+ stack.push(5 )
52
+
53
+ println (stack.pop()) // 5
54
+ println (stack.pop()) // 7
55
+ println (stack.pop()) // 5
56
+ println (stack.pop()) // 4
57
+ }
0 commit comments