Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
- get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
- put(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.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
設計並實作一個稱作最久未使用(LRU)快取的資料結構。它支援以下運算:get 和 put。
- get(key) - 如果該key存在就取得該key的value(確保它是正數),否則回傳-1。
- put(key, value) - 賦值或是插入一個value當該key不存在。如果快取已經到它的上限了,使最久未使用的項目失效並加入新的項目。
time
來記錄每個資料最後被使用的時間;而每次動作都會讓time++
。pair
來綁時間和值綁起來,再用map
把value
和pair
綁起來。min_element
去找到並移除time
最小的項目。get
使用hash加速,在這邊的unordered_map
就是。put
的部分可以使用linked-list來實作,根據time
來串起來的話,就可以直接在頭尾加入移除。LeetCode
C++