-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
88 lines (77 loc) · 1.38 KB
/
main.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
package _0146
type LRUCache struct {
cap int
m map[int]*Node
head *Node
tail *Node
}
type Node struct {
key int
value int
prev *Node
next *Node
}
func Constructor(capacity int) LRUCache {
c := LRUCache{
cap: capacity,
m: map[int]*Node{},
head: &Node{},
tail: &Node{},
}
c.head.next = c.tail
c.tail.prev = c.head
return c
}
func (this *LRUCache) Get(key int) int {
node, ok := this.m[key]
if !ok {
return -1
}
this.addToFirst(node)
return node.value
}
func (this *LRUCache) addToFirst(node *Node) {
if this.head.next == node {
return
}
firstOld := this.head.next
prev := node.prev
next := node.next
if prev != nil {
prev.next = next
}
if next != nil {
next.prev = prev
}
firstOld.prev = node
node.next = firstOld
node.prev = this.head
this.head.next = node
this.m[node.key] = node
}
func (this *LRUCache) removeLast() {
last := this.tail.prev
delete(this.m, last.key)
prev := last.prev
this.tail.prev = prev
prev.next = this.tail
}
func (this *LRUCache) Put(key int, value int) {
node, ok := this.m[key]
if ok {
node.value = value
} else {
node = &Node{key: key, value: value}
}
this.addToFirst(node)
this.m[key] = node
if len(this.m) > this.cap {
this.removeLast()
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/