-
Notifications
You must be signed in to change notification settings - Fork 0
/
2021-11-04_medium_lru-cache.rb
84 lines (73 loc) · 1.68 KB
/
2021-11-04_medium_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
75
76
77
78
79
80
81
82
83
84
# https://leetcode.com/problems/lru-cache/submissions/
class Node
attr_accessor :key, :value, :next, :prev
def initialize(key = nil, value = nil)
@key = key
@value = value
end
end
class LRUCache
=begin
:type capacity: Integer
=end
def initialize(capacity)
@capacity = capacity
@head = Node.new()
@tail = Node.new()
@head.next = @tail
@tail.prev = @head
@map = {}
end
=begin
:type key: Integer
:rtype: Integer
=end
def get(key)
node = @map[key]
if node
moveNodeToTail(node)
return node.value
else
return -1
end
end
=begin
:type key: Integer
:type value: Integer
:rtype: Void
=end
def put(key, value)
node = @map[key]
if node
@map[key].value = value
moveNodeToTail(node)
return node.value
else
if @map.size == @capacity
@map.delete(@head.next.key)
removeNode(@head.next)
end
node = Node.new(key, value)
addNodeToTail(node)
@map[key] = node
end
end
def removeNode(node)
node.prev.next = node.next
node.next.prev = node.prev
end
def addNodeToTail(node)
node.next = @tail
node.prev = @tail.prev
@tail.prev.next = node
@tail.prev = node
end
def moveNodeToTail(node)
self.removeNode(node)
self.addNodeToTail(node)
end
end
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache.new(capacity)
# param_1 = obj.get(key)
# obj.put(key, value)