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.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
解法1: HashMap + Deque
O(1)的put和get,hashmap应该是逃不了的。问题是还要维护每一个value的access的时间的先后顺序,一般的解法给出来的办法是用一个deque,最近access过的东西放在deque的最后面,而head就存放将要被删除的value。
那么自己要实现的deque的操作就是move_to_head还有一个是remove_from_head,写的时候别忘了当capacity满了之后,需要从deque和hashmap两个地方都删除掉才行。
|
|