設計和構建一個“最近最少使用”快取,該快取會洗掉最近最少使用的專案,快取應該從鍵映射到值(允許你插入和檢索特定鍵對應的值),并在初始化時指定最大容量,當快取被填滿時,它應該洗掉最近最少使用的專案,
它應該支持以下操作: 獲取資料 get 和 寫入資料 put ,
獲取資料 get(key) - 如果密鑰 (key) 存在于快取中,則獲取密鑰的值(總是正數),否則回傳 -1,
寫入資料 put(key, value) - 如果密鑰不存在,則寫入其資料值,當快取容量達到上限時,它應該在寫入新資料之前洗掉最近最少使用的資料值,從而為新的資料值留出空間,
示例:
LRUCache cache = new LRUCache( 2 /* 快取容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 回傳 1
cache.put(3, 3); // 該操作會使得密鑰 2 作廢
cache.get(2); // 回傳 -1 (未找到)
cache.put(4, 4); // 該操作會使得密鑰 1 作廢
cache.get(1); // 回傳 -1 (未找到)
cache.get(3); // 回傳 3
cache.get(4); // 回傳 4
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/lru-cache-lcci

解題:
import java.util.HashMap; import java.util.LinkedList; class LRUCache {
private int capacity; private HashMap<Integer, Integer> map; private LinkedList<Integer> list; public LRUCache(int capacity) { this.capacity = capacity; map = new HashMap<>(); list = new LinkedList<>(); } public int get(int key) { if (map.containsKey(key)) { list.remove(key); list.addLast(key); return map.get(key); } return -1; } public void put(int key, int value) { // 1 如果包含這個key if (map.containsKey(key)) { list.remove(key); list.addLast(key); map.put(key, value); return; } //2 不包含這個key if (list.size() == capacity) { // 移除 Integer integer = list.removeFirst(); map.remove(integer); list.addLast(key); map.put(key, value); } else { list.addLast(key); map.put(key, value); } } } /** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/137101.html
標籤:Java
