Skip to content

Create 0146-LRU-Cache.rb #1309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions ruby/146-LRU-Cache.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy