Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fe9b8d9

Browse files
author
konstantin
committed
Hard895 challenge
1 parent 1286cde commit fe9b8d9

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /