forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru-cache.go
executable file
·76 lines (69 loc) · 1.82 KB
/
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package problem0146
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/
import "container/list"
// LRUCache contains a hash map and a doubly linked list
type LRUCache struct {
cap int // capacity
l *list.List // doubly linked list
m map[int]*list.Element // hash table for checking if list node exists
}
// Pair is the value of a list node.
type Pair struct {
key int
value int
}
// Constructor initializes a new LRUCache.
func Constructor(capacity int) LRUCache {
return LRUCache{
cap: capacity,
l: new(list.List),
m: make(map[int]*list.Element, capacity),
}
}
// Get a list node from the hash map.
func (c *LRUCache) Get(key int) int {
// check if list node exists
if node, ok := c.m[key]; ok {
val := node.Value.(*list.Element).Value.(Pair).value
// move node to front
c.l.MoveToFront(node)
return val
}
return -1
}
// Put key and value in the LRUCache
func (c *LRUCache) Put(key int, value int) {
// check if list node exists
if node, ok := c.m[key]; ok {
// move the node to front
c.l.MoveToFront(node)
// update the value of a list node
node.Value.(*list.Element).Value = Pair{key: key, value: value}
} else {
// delete the last list node if the list is full
if c.l.Len() == c.cap {
// get the key that we want to delete
idx := c.l.Back().Value.(*list.Element).Value.(Pair).key
// delete the node pointer in the hash map by key
delete(c.m, idx)
// remove the last list node
c.l.Remove(c.l.Back())
}
// initialize a list node
node := &list.Element{
Value: Pair{
key: key,
value: value,
},
}
// push the new list node into the list
ptr := c.l.PushFront(node)
// save the node pointer in the hash map
c.m[key] = ptr
}
}