leetcode LRU cache

题目:

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.

 就是设计一个数据结构,模拟缓存的操作。

一开始想到使用队列,但是TLE。

后来考虑到每次淘汰cache时,我只需要知道最旧的那个cache,而不需要知道具体的cache的排序,想到

一个数据结构,堆。设置一个index,表示cache插入的顺序。维持一个index作为特征值的堆。

在具体实现时,用一个HashMap存储key和该堆中节点的对应关系。这样,每次

淘汰时,只需将堆头淘汰掉,然后将新的cache放入堆中,再调整堆满足条件。而hashMap中存储的是key和堆的节点的对应关系。

这个方法AC了。

稍微查了一下,有个更好的办法,即依然使用队列实现,但是队列用链表实现。

然而用一个HashMap表征key和队列中节点的对应关系,这样可以保证快速找到队列中的节点。

 
 
原文地址:https://www.cnblogs.com/elnino/p/5607783.html