1. 程式人生 > 其它 >【每日一題】【模擬】2021年11月11日--LRU 快取機制

【每日一題】【模擬】2021年11月11日--LRU 快取機制

運用你所掌握的資料結構,設計和實現一個 LRU (最近最少使用) 快取機制 。
實現 LRUCache 類:

LRUCache(int capacity) 以正整數作為容量 capacity 初始化 LRU 快取
int get(int key) 如果關鍵字 key 存在於快取中,則返回關鍵字的值,否則返回 -1 。
void put(int key, int value) 如果關鍵字已經存在,則變更其資料值;如果關鍵字不存在,則插入該組「關鍵字-值」。當快取容量達到上限時,它應該在寫入新資料之前刪除最久未使用的資料值,從而為新的資料值留出空間。

進階:你是否可以在 O(1) 時間複雜度內完成這兩種操作?

class LRUCache {

    public int cap;
    public Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
    public LRUCache(int capacity) {
        this.cap = capacity;
    }

    public int get(int key) {
        if (map.containsKey(key)) {
            int value = map.get(key);
            map.remove(key);
            map.put(key,value);
            
return value; } return -1; } public void put(int key, int value) { if (map.containsKey(key)) { map.remove(key); } else if (map.size() == cap) { Iterator<Integer> iterator = map.keySet().iterator(); iterator.next(); iterator.remove(); } map.put(key, value); } }

本文來自部落格園,作者:劉金輝,轉載請註明原文連結:https://www.cnblogs.com/liujinhui/p/15541617.html