日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】LRU Cache 解决报告

發布時間:2025/3/20 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】LRU Cache 解决报告 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

插話:只寫了幾個連續的博客,博客排名不再是實際“遠在千里之外”該。我們已經進入2一萬內。

再接再厲。油!

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:?get?and?set.

get(key)?- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value)?- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

【題意】

設計并實現一個支持get和set操作的緩存:

get(key) - 存在時返回其值。否則返回-1。

set(key) - 不存在時插入新值。存在時更新其值。注意當容量滿時,需刪除最長時間沒有訪問的key。將其刪除。并插入新的key。


==================== Map+List 實現法 ====================

【思路】

用map結構實現<key, value>的存儲與讀取。

用一個list來記錄key被訪問時間的久遠。近期被訪問的放在list的最后。list中的第一個key表示最長時間沒被訪問的。

【Java代碼】

class LRUCache {HashMap<Integer, Integer> map;ArrayList<Integer> list;int capacity;public LRUCache(int capacity) {map = new HashMap<Integer, Integer>(capacity);list = new ArrayList<Integer>(capacity);this.capacity = capacity;}public int get(int key) {if (map.get(key) == null) return -1;list.remove(new Integer(key)); list.add(key);return map.get(key);}public void set(int key, int value) {if (map.get(key) != null) {//原來存在keymap.put(key, value);list.remove(new Integer(key)); list.add(key);} else {//原來不存在keyif (map.size() < capacity) {//容量不滿map.put(key, value);list.add(key);} else {//容量滿int leastkey = list.remove(0);list.add(key);map.remove(leastkey);map.put(key, value);}}} }

【注意點】

題目要求是Least Recently Used,不僅 set 時要更新list,get 時也要更新list。

set 時。需先推斷map中有無該值,若沒有再推斷map是否滿了;假設反過來,即先推斷map是否為滿,再推斷map中有無該值。這樣就錯了。

由于假設map滿時,當中有該值。直接更新就好,而先推斷map是否為滿的話。就會導致刪除最長時間沒有被訪問的值。


【常規解法】

通經常使用的元素雙向鏈表來記錄不被訪問的時間最長,由于雙向鏈表可以O(1)達到一定時間內移動的節點,刪除頭和尾節點。

在上面的代碼list實現,其remove當實際遍歷整個list為了找到一個節點。

LeetCode沒有時間作要求,采訪中肯定會要求。


總結

以上是生活随笔為你收集整理的【LeetCode】LRU Cache 解决报告的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。