forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0146-lru-cache.go
62 lines (52 loc) · 1.36 KB
/
0146-lru-cache.go
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
type Node struct {
key int
val int
prev *Node
next *Node
}
type LRUCache struct {
capacity int
cache map[int]*Node
left *Node
right *Node
}
func Constructor(capacity int) LRUCache {
ret := LRUCache {
capacity: capacity,
cache: make(map[int]*Node),
left: &Node{key: 0, val: 0},
right: &Node{key: 0, val: 0}}
ret.left.next, ret.right.prev = ret.right, ret.left
return ret
}
func (this *LRUCache) Remove(node *Node) {
prev, nxt := node.prev, node.next
prev.next, nxt.prev = nxt, prev
}
func (this *LRUCache) Insert(node *Node) {
prev, nxt := this.right.prev, this.right
nxt.prev = node
prev.next = nxt.prev
node.next, node.prev = nxt, prev
}
func (this *LRUCache) Get(key int) int {
if _, ok := this.cache[key]; ok {
this.Remove(this.cache[key])
this.Insert(this.cache[key])
return this.cache[key].val
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if _, ok := this.cache[key]; ok {
this.Remove(this.cache[key])
}
this.cache[key] = &Node{key: key, val: value}
this.Insert(this.cache[key])
if len(this.cache) > this.capacity {
// remove from the list and delete the LRU from hashmap
lru := this.left.next
this.Remove(lru)
delete(this.cache, lru.key)
}
}