-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0146-lru-cache.rb
74 lines (60 loc) · 1.3 KB
/
0146-lru-cache.rb
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
class LRUCache
=begin
:type capacity: Integer
=end
def initialize(capacity)
@capacity = capacity
@cache = {}
@l = Node.new()
@r = Node.new()
@l.next = @r
@r.prev = @l
end
=begin
:type key: Integer
:rtype: Integer
=end
def get(key)
return -1 unless @cache.key?(key)
remove(@cache[key])
insert(@cache[key])
@cache[key].value
end
=begin
:type key: Integer
:type value: Integer
:rtype: Void
=end
def put(key, value)
remove(@cache[key]) if @cache.key?(key)
@cache[key] = Node.new(key, value)
insert(@cache[key])
evict if @capacity < @cache.size
end
private
def remove(node)
prev = node.prev
nxt = node.next
prev.next = nxt
nxt.prev = prev
end
def insert(node)
prev = @r.prev
prev.next = node
@r.prev = node
node.prev = prev
node.next = @r
end
def evict
lru = @l.next
remove(lru)
@cache.delete(lru.key)
end
class Node
attr_accessor :value, :prev, :next, :key
def initialize(key = 0, val = nil)
self.value = val
self.key = key
end
end
end