Ruby AC using hash


  • 0
    T

    Ruby hashes are sorted, so we can delete keys, add keys, and shift the hash to remove least used.

    class LRUCache
    
        def initialize(capacity)
            @capacity = capacity
            @values = {}
        end
    
    
        def get(key)
            # puts @values.to_s
            if @values[key]
                value = @values[key]
                @values.delete(key)
                @values[key] = value
                # puts "after delete: " + @values.to_s
                @values.shift if @values.length > @capacity
                return value
            else
                return -1
            end
        end
    
    
        def put(key, value)
            @values.delete(key)
            @values[key] = value
            if @values.length > @capacity
                @values.shift
            end
        end
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.