zoukankan      html  css  js  c++  java
  • LRU算法

    golang实现,比较简单的版本

    package lru
    
    import "container/list"
    
    type Node struct {
        K, V interface{}
    }
    
    type LRU struct {
        list *list.List
        cacheMap map[interface{}]*list.Element
        Size int
    }
    
    func NewLRU(cap int) *LRU {
        return &LRU{
            Size: cap,
            list: list.New(),
            cacheMap: make(map[interface{}]*list.Element, cap),
        }
    }
    
    func (lru *LRU) Get(k interface{}) (v interface{}, ret bool) {
        if ele, ok := lru.cacheMap[k]; ok {
            lru.list.MoveToFront(ele)
            return ele.Value.(*Node).V, true
        }
    
        return nil, false
    }
    
    func (lru *LRU) Set(k, v interface{}) {
        if ele, ok := lru.cacheMap[k]; ok {
            lru.list.MoveToFront(ele)
            ele.Value.(*Node).V = v
            return
        }
    
        if lru.list.Len() == lru.Size {
            last := lru.list.Back()
            node := last.Value.(*Node)
            delete(lru.cacheMap, node.K)
            lru.list.Remove(last)
        }
    
        ele := lru.list.PushFront(&Node{k, v})
        lru.cacheMap[k] = ele
    }

    end

  • 相关阅读:
    Java线程死锁模拟
    Arrays Multi
    PHP Forms
    simple grammer
    有意义的命名 Meaningful names
    整洁代码
    XPath
    多态
    复用类
    访问控制权限
  • 原文地址:https://www.cnblogs.com/CherryTab/p/13212660.html
Copyright © 2011-2022 走看看