-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146-lru-cache.go
105 lines (85 loc) · 1.84 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"container/list"
"fmt"
)
// https://leetcode-cn.com/problems/lru-cache/
type intMap map[int]*list.Element
func (m intMap) get(key int) *list.Element {
return m[key]
}
func (m intMap) add(key int, e *list.Element) {
m[key] = e
}
func (m intMap) len() int {
return len(m)
}
func (m intMap) delete(key int) {
delete(m, key)
}
type LRUCache struct {
capacity int
dict intMap
list *list.List
}
type kv struct {
key int
value int
}
func Constructor(capacity int) LRUCache {
return LRUCache{
dict: make(intMap, capacity),
list: list.New(),
capacity: capacity,
}
}
func (this *LRUCache) len() int {
dictLen := this.dict.len()
listLen := this.list.Len()
if dictLen != listLen {
err := fmt.Errorf("bug: length mismatch, dict len: %v, list len: %v", dictLen, listLen)
panic(err)
}
return dictLen
}
func (this *LRUCache) lruElement() *list.Element {
return this.list.Front()
}
func (this *LRUCache) touchElement(e *list.Element) {
this.list.MoveToBack(e)
}
func (this *LRUCache) deleteElement(e *list.Element) {
key := this.list.Remove(e).(kv).key
this.dict.delete(key)
}
func (this *LRUCache) Get(key int) int {
if e := this.dict.get(key); e != nil {
this.touchElement(e)
return e.Value.(kv).value
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if this.capacity <= 0 {
return
}
// found then update its value
if e := this.dict.get(key); e != nil {
e.Value = kv{key: key, value: value}
this.touchElement(e)
return
}
// full, remove the LRU element
if this.len() >= this.capacity {
e := this.lruElement()
this.deleteElement(e)
}
e := this.list.PushBack(kv{key: key, value: value})
this.dict.add(key, e)
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/