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 de6e0be

Browse files
committed
Solve 460. LFU Cache
1 parent e2b638d commit de6e0be

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

‎04/0460-LFU_Cache.kt

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class LFUCache(private val capacity: Int) {
2+
3+
private data class Item(var value: Int, var frequency: Int)
4+
5+
private var minFrequency = 0
6+
private val items = hashMapOf<Int, Item>()
7+
private val frequencySets = hashMapOf<Int, MutableSet<Int>>()
8+
9+
private fun getItem(key: Int): Item? {
10+
val item = items.get(key) ?: return null
11+
val frequencySet = frequencySets.get(item.frequency)!!
12+
13+
frequencySet.remove(key)
14+
15+
if (minFrequency == item.frequency && frequencySet.isEmpty()) {
16+
minFrequency += 1
17+
}
18+
19+
item.frequency += 1
20+
frequencySets.getOrPut(item.frequency) { mutableSetOf() }.add(key)
21+
22+
return item
23+
}
24+
25+
26+
fun get(key: Int): Int {
27+
return getItem(key)?.value ?: -1
28+
}
29+
30+
fun put(key: Int, value: Int) {
31+
if (capacity == 0) return
32+
33+
val item = getItem(key)
34+
35+
if (item != null) {
36+
item.value = value
37+
} else {
38+
val newItem = Item(value, 1)
39+
40+
if (items.size == capacity) {
41+
val frequencySet = frequencySets.get(minFrequency)!!
42+
val keyToRemove = frequencySet.first()
43+
44+
frequencySet.remove(keyToRemove)
45+
items.remove(keyToRemove)
46+
}
47+
48+
minFrequency = 1
49+
items[key] = newItem
50+
frequencySets.getOrPut(1) { mutableSetOf() }.add(key)
51+
}
52+
}
53+
54+
}
55+
56+
/**
57+
* Your LFUCache object will be instantiated and called as such:
58+
* var obj = LFUCache(capacity)
59+
* var param_1 = obj.get(key)
60+
* obj.put(key,value)
61+
*/

0 commit comments

Comments
(0)

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