-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0146-lru-cache.kt
58 lines (51 loc) · 1.44 KB
/
0146-lru-cache.kt
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
package kotlin
private class Node(
val key: Int,
var value: Int,
var next: Node? = null,
var previous: Node? = null
)
class LRUCache(private val capacity: Int) {
private val head = Node(0, 0)
private val tail = Node(0, 0)
private val hashMap = HashMap<Int, Node>()
init {
head.next = tail
tail.previous = head
}
fun get(key: Int): Int {
if (key !in hashMap) return -1
val nodeToBeRemoved = hashMap.getValue(key)
removeNode(nodeToBeRemoved)
insertAtEnd(nodeToBeRemoved)
return nodeToBeRemoved.value
}
fun put(key: Int, value: Int) {
if (key in hashMap) {
val nodeToBeMoved = hashMap.getValue(key).apply { this.value = value }
removeNode(nodeToBeMoved)
insertAtEnd(nodeToBeMoved)
return
}
if (hashMap.size == capacity) {
val nodeToRemove = head.next!!
removeNode(nodeToRemove)
hashMap.remove(nodeToRemove.key)
}
val newNode = Node(key, value)
insertAtEnd(newNode)
hashMap[key] = newNode
}
private fun insertAtEnd(node: Node) {
node.apply {
previous = tail.previous
next = tail
}
tail.previous!!.next = node
tail.previous = node
}
private fun removeNode(node: Node) {
node.previous?.next = node.next
node.next?.previous = node.previous
}
}