-
Notifications
You must be signed in to change notification settings - Fork 0
/
146.lru-cache.go
92 lines (75 loc) · 1.71 KB
/
146.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* @lc app=leetcode id=146 lang=golang
*
* [146] LRU Cache
*/
// @lc code=start
// Use a HashMap + doubly-linked list (container/list) to implement cache
// type Element struct {
// // The value stored with this element.
// Value any
// // contains filtered or unexported fields
// }
type Pair struct {
Key int
Val int
}
type LRUCache struct {
l *list.List
m map[int]*list.Element
capacity int
}
func Constructor(capacity int) LRUCache {
return LRUCache{
list.New(),
make(map[int]*list.Element, capacity),
capacity,
}
}
func (this *LRUCache) Get(key int) int {
if node, exsit := this.m[key]; exsit {
// move the node to front
this.l.MoveToFront(node)
return node.Value.(*list.Element).Value.(Pair).Val
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
// if cache hit
if node, exsit := this.m[key]; exsit {
// update the value of this node
p := node.Value.(*list.Element).Value = Pair{
key,
value,
}
// move the node to front
this.l.MoveToFront(node)
// if cache miss
} else {
// push the new node into list, PushFront returns *Element
ptr := this.l.PushFront(&list.Element{
Value: Pair{
Key: key,
Val: value,
},
})
// add the new item into map
this.m[key] = ptr
// if cache is overflow
if this.l.Len() > this.capacity {
// find the last node we want to delete
lastKey := this.l.Back().Value.(*list.Element).Value.(Pair).Key
// delete the item in map
delete(this.m, lastNode.Key)
// delete the node
this.l.Remove(this.l.Back())
}
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/
// @lc code=end