-
Notifications
You must be signed in to change notification settings - Fork 0
/
20190728-146.lru-cache.go
82 lines (73 loc) · 1.51 KB
/
20190728-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
package main
/*
* @lc app=leetcode id=146 lang=golang
*
* [146] LRU Cache
*/
// Node146 : 双向链表结点
type Node146 struct {
key int
val int
prev, next *Node146
}
// LRUCache :
type LRUCache struct {
capacity int
cache map[int]*Node146
head, tail *Node146
}
// Constructor :
func Constructor146(capacity int) LRUCache {
m := LRUCache{
capacity: capacity,
cache: make(map[int]*Node146, capacity),
head: new(Node146),
tail: new(Node146),
}
m.head.next, m.tail.prev = m.tail, m.head
return m
}
// Get : 读
func (m *LRUCache) Get(key int) int {
if node, ok := m.cache[key]; ok {
m.moveToEnd(node)
return node.val
} else {
return -1
}
}
// Put : 写
func (m *LRUCache) Put(key int, value int) {
if node, ok := m.cache[key]; ok {
node.val = value
m.moveToEnd(node)
} else {
if len(m.cache) == m.capacity {
// delete first
first := m.head.next
delete(m.cache, first.key)
m.head.next, first.next.prev = first.next, m.head
}
node := &Node146{
key: key,
val: value,
}
m.cache[key] = node
m.insertToEnd(node)
}
}
func (m *LRUCache) insertToEnd(node *Node146) {
node.prev, node.next = m.tail.prev, m.tail
node.prev.next, node.next.prev = node, node
}
func (m *LRUCache) moveToEnd(node *Node146) {
// unlink
node.prev.next, node.next.prev = node.next, node.prev
m.insertToEnd(node)
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/