-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru_cache.go
91 lines (76 loc) · 1.43 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// https://leetcode.com/problems/lru-cache/
package lru_cache
type CacheNode struct {
key int
val int
ts int64
}
type LRUCache struct {
data []*CacheNode
dataIdxByKey map[int]int
idx int
}
var (
curTime int64 = 0
)
func Constructor(capacity int) LRUCache {
curTime++
return LRUCache{
make([]*CacheNode, capacity),
make(map[int]int),
0,
}
}
func (this *LRUCache) Get(key int) int {
curTime++
if this.idx == 0 {
return -1
}
i := this.getKeyIdx(key)
if i == -1 {
return -1
}
this.data[i].ts = curTime
return this.data[i].val
}
func (this *LRUCache) Put(key int, value int) {
curTime++
freeIdx := this.getKeyIdx(key)
if freeIdx == -1 {
// If cache is full - find LRU element
if this.idx == len(this.data) {
minTime := int64(1<<63 - 1)
for i := 0; i < len(this.data); i++ {
if minTime > this.data[i].ts {
freeIdx = i
minTime = this.data[i].ts
}
}
if freeIdx != -1 {
delete(this.dataIdxByKey, this.data[freeIdx].key)
}
} else {
freeIdx = this.idx
this.idx++
}
}
// Add
this.data[freeIdx] = &CacheNode{
key: key,
val: value,
ts: curTime,
}
this.dataIdxByKey[key] = freeIdx
}
func (this *LRUCache) getKeyIdx(key int) int {
if i, ok := this.dataIdxByKey[key]; ok {
return i
}
return -1
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/