最近github上有个很火的面试相关的项目短短几天时间就进入了trending首页,项目是关于国内几家互联网大公司的面试题以及答案,里面有很多算法题都值得刷一刷。本篇主要讲阿里面试题里面的LRU缓存机制,github上附有答案,遗憾的是只有python版和C++版本的,没有Java版本的...无fuck说,Java但是世界排名第一的语言!!!node
LRU 缓存机制 设计和实现一个 LRU(最近最少使用)缓存数据结构,使它应该支持一下操做:get 和 put。 get(key) - 若是 key 存在于缓存中,则获取 key 的 value(老是正数),不然返回 -1。 put(key,value) - 若是 key 不存在,请设置或插入 value。当缓存达到其容量时,它应该在插入新项目以前使最近最少使用的项目做废。python
LRU是Least Recently Used的缩写,即最近最少使用。根据题意须要手写一个LRU算法,事实上在LeetCode上搜LRU即可以搜到146. LRU Cache,对比下面试题是一摸同样。为了方便结果验证,咱们直接来看LeetCode原题。git
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.github
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?缓存
Example:bash
LRUCache cache = new LRUCache( 2 /* capacity */ );微信
cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4数据结构
设计和实现一个LRU(最近最少使用)的缓存机制。它能够支持如下操做: get 和 put 。
获取数据 get(key) - 若是 (key) 存在于缓存中,则获取值(老是正数),不然返回 -1。 写入数据 put(key, value) - 若是key不存在,则写入其数据值。当缓存容量达到上限时,在写入新数据以前删除最近最少使用的数据,从而为新的数据留出空间。
进阶:
你可否在 O(1) 时间复杂度内完成?
例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1); cache.put(2, 2); cache.get(1); // 返回 1 cache.put(3, 3); // 该操做会使得key 2 做废 cache.get(2); // 返回 -1 (未找到) cache.put(4, 4); // 该操做会使得key 1 做废 cache.get(1); // 返回 -1 (未找到) cache.get(3); // 返回 3 cache.get(4); // 返回 4
考虑到题目中的最近最少,咱们显然能联想到使用队列结构。结合题意,为了尽量的提升插入和查找的效率,保证时间复杂度在O(1),最大程度的提升get和put的速度,必然要使用双向链表队列(单链表须要遍历才能插入节点,时间复杂度高)。而在实现了双向链表队列结构以后还须要考虑两点:一、插入数据put达到数量上限时,删除最老节点(最长时间未被使用),即链表队列的尾部节点,由于尾部节点是最晚插入的;二、获取数据get到数据时,须要将当前获取到的节点移动到队列头部,由于最近被使用了。
public class LRUCache {
/**
*
* Node类用于抽象链表的节点
* key、value存储键、值,
* before、after分别指向当前节点的先后Node节点;
*
*/
class Node {
int key;
int value;
Node before;
Node after;
}
/**
* 使用HashMap缓存Node节点
*/
private HashMap<Integer, Node> cache = new HashMap<Integer, Node>();
/**
* 最大容量,超过capacity时继续插入会触发删除最老未被使用的节点
*/
private int capacity;
/**
* 头节点、尾节点(注意这两个节点不存储实际的数据)
*/
private Node head, tail;
public LRUCache(int capacity) {
this.capacity = capacity;
head = new Node();
head.before = null;
tail = new Node();
tail.after = null;
head.after = tail;
tail.before = head;
}
/**
* 将节点插入队列头部
*
* @param node
*/
private void addToHead(Node node) {
node.before = head;
node.after = head.after;
head.after.before = node;
head.after = node;
}
/**
* 删除队列中的一个节点
*
* @param node
*/
private void removeNode(Node node) {
Node before = node.before;
Node after = node.after;
before.after = after;
after.before = before;
}
/**
* 将节点移动到有效数据头部
*
* @param node
*/
private void moveToHead(Node node) {
removeNode(node);
addToHead(node);
}
/**
* 删除有效数据尾节点
*
* @return 尾节点
*/
private Node popTail() {
Node res = tail.before;
this.removeNode(res);
return res;
}
public int get(int key) {
Node node = cache.get(key);
if (node == null) {
return -1; // should raise exception here.
}
// 若是获取到数据,则将获取到的节点移动到队列头部;
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
Node node = cache.get(key);
if (node == null) {
Node newNode = new Node();
newNode.key = key;
newNode.value = value;
cache.put(key, newNode);
addToHead(newNode);
if (cache.size() > capacity) {
// 删除队尾有效数据节点
Node tail = this.popTail();
this.cache.remove(tail.key);
}
} else {
node.value = value;
// 在使用get方法获取值以后,须要将当前获取的节点移动到队列头部
moveToHead(node);
}
}
}
复制代码
见代码注释
事实上Java标准库里提供了能够直接使用的LRU思想的数据结构,即LinkedHashMap,其底层实现原理和方法一是一致的
class LRUCache extends LinkedHashMap<Integer,Integer> {
private int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75F,true);
this.capacity = capacity;
}
public int get(int key) {
return super.getOrDefault(key,-1);
}
public void put(int key, int value) {
super.put(key,value);
}
@Override
public boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest){
return size() > capacity;
}
}
复制代码
LinkedHashMap提供了能够覆写的removeEldestEntry方法,removeEldestEntry方法的做用直接参考LinkedHashMap源码:
/**
* Returns <tt>true</tt> if this map should remove its eldest entry.
* This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
* inserting a new entry into the map. It provides the implementor
* with the opportunity to remove the eldest entry each time a new one
* is added. This is useful if the map represents a cache: it allows
* the map to reduce memory consumption by deleting stale entries.
*
* <p>Sample use: this override will allow the map to grow up to 100
* entries and then delete the eldest entry each time a new entry is
* added, maintaining a steady state of 100 entries.
* <pre>
* private static final int MAX_ENTRIES = 100;
*
* protected boolean removeEldestEntry(Map.Entry eldest) {
* return size() > MAX_ENTRIES;
* }
* </pre>
*
* <p>This method typically does not modify the map in any way,
* instead allowing the map to modify itself as directed by its
* return value. It <i>is</i> permitted for this method to modify
* the map directly, but if it does so, it <i>must</i> return
* <tt>false</tt> (indicating that the map should not attempt any
* further modification). The effects of returning <tt>true</tt>
* after modifying the map from within this method are unspecified.
*
* <p>This implementation merely returns <tt>false</tt> (so that this
* map acts like a normal map - the eldest element is never removed).
*
* @param eldest The least recently inserted entry in the map, or if
* this is an access-ordered map, the least recently accessed
* entry. This is the entry that will be removed it this
* method returns <tt>true</tt>. If the map was empty prior
* to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
* in this invocation, this will be the entry that was just
* inserted; in other words, if the map contains a single
* entry, the eldest entry is also the newest.
* @return <tt>true</tt> if the eldest entry should be removed
* from the map; <tt>false</tt> if it should be retained.
*/
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
复制代码
大概意思是在新插入一个节点时,删除最老的节点,在缓存数据时能够用到(简直是LRU思想的量身定作)。另外若是使用默认false的话,表示容器没有限制大小,不删除最老未被使用的节点,至关于使用普通的Map。
还能够注意到注释中有一段很醒目的demo写法:
private static final int MAX_ENTRIES = 100;
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
复制代码
本题中因为限制条件为超过队列最大值限制大小即开始删除最老节点,所以使用size() > capacity判断条件。注意到get方法不是直接调用而是使用的getOrDefault(key,-1)是因为题目描述当get拿不到数据时默认返回-1。
观察方法一手写双向链表的实现,addToHead将节点添加到头部方法以及popTail删除尾节点的方法,分别是添加节点到头部第二个节点,以及删除倒数第二个节点,这是为何呢?这即是本篇的彩蛋。
针对阿里的LRU面试题,本题分析了两种解法。我的猜想阿里出题者的出题思路是考察LRU思想的理解,在理解思想的基础上可能会进一步延伸到LinkedHashMap的源码,LinkedHashMap熟悉了会伪装不经意继续深刻到它的父类HashMap,到了HashMap确定继续会问你负载因子,Hash碰撞,红黑树裂变,左右旋扯完了HashMap再和你谈谈HashTable和区别...你会发现总有一处可能命中你的盲点,是否是细思极恐,哈哈~不要方,扫一扫,关注个人微信订阅号,后续会有针对相似LinkedHashMap等比较重要的数据结构的源码分析系列文章,敬请期待!最后,若是以为本文对你有所帮助或启发那就来个赞吧0.0