LRU緩存機制

問題: 運用你所掌握的數據結構,設計和實現一個 LRU (最近最少使用) 緩存機制。它應該支持以下操作: 獲取數據 get 和 寫入數據 put 。
獲取數據 get(key) - 如果密鑰 (key) 存在於緩存中,則獲取密鑰的值(總是正數),否則返回 -1。
寫入數據 put(key, value) - 如果密鑰不存在,則寫入其數據值。當緩存容量達到上限時,它應該在寫入新數據之前刪除最近最少使用的數據值,從而爲新的數據值留出空間。
你是否可以在 O(1) 時間複雜度內完成這兩種操作?

思路: 使用雙向鏈表保存元素,每次訪問和插入的元素移動到頭部;利用哈希表進行查詢。

java代碼:

public class LRUCache {
    public class Item {
        int key;
        int value;
        Item prev,next;
        Item(int key,int value){
            this.key=key;
            this.value=value;
            this.prev=null;
            this.next=null;
        }
        Item(){
            this.key=0;
            this.value=0;
            this.prev=null;
            this.next=null;
        }
    }
    Item m_start,m_end;
    int capacity,curr_size;
    HashMap<Integer,Item> m_hm;
    LRUCache(int capacity){
        this.capacity=capacity;
        curr_size=0;
        m_start=null;
        m_end=null;
        m_hm=new HashMap<Integer, Item>();
    }
    int get(int key){
        if(m_hm.containsKey(key)){
            Item cur=m_hm.get(key);

            if(cur.prev!=null) {
                if(cur.next==null){
                    m_end=cur.prev;
                }else{
                    cur.next.prev = cur.prev;
                }

                cur.prev.next = cur.next;
                cur.next = m_start;
                m_start.prev = cur;
                m_start = cur;
                cur.prev=null;
            }
            return cur.value;
        }else{
            return -1;
        }
    }

    void put(int key,int value){
        if(get(key)==-1){
            Item newItem=new Item(key,value);
            newItem.next=m_start;
            if(m_start!=null){
                m_start.prev=newItem;
            }else{
                m_end=newItem;
            }
            m_start=newItem;
            m_hm.put(key,newItem);
            if(curr_size>=capacity){
                m_hm.remove(m_end.key);
                m_end=m_end.prev;
                m_end.next=null;

            }else{
                curr_size++;
            }
        }else{
            m_hm.get(key).value=value;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章