面试经典实现LRU Cache

你遇到过这个题吗?

实现一个LRU Cache。要求查询和插入都在O(1) 时间内完成。

遇到过?很正常。

没遇到?早晚会遇到。(鬼脸)

这是LeetCode上一道十分经典的题目,也是非常火的面试题。

原题:

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.

根据操作系统所学:cache(缓存)可以帮助快速存取数据,但是容量小。

本题要求实现的是LRU cache,LRU的思想来自“最近用到的数据被重用的概率比最早用到的数据大的多”,是一种十分高效的cache。

解决本题的方法是:双向链表+HashMap。

注: HashMap O(1)大家都懂。

对于双向链表的使用,基于两个考虑。

首先,Cache中块的命中是随机的,和Load进来的顺序无关。

其次,双向链表插入、删除很快,可以灵活的调整相互间的次序,时间复杂度为O(1)。

新建数据类型Node节点,Key-Value值,并有指向前驱节点后后继节点的指针,构成双向链表的节点。

<span style="font-size:18px;">class Node {
	int key;
	int value;
	Node pre;
	Node next;
 
	public Node(int key, int value) {
		this.key = key;
		this.value = value;
	}
	
	@Override
	public String toString() {
		return this.key + "-" + this.value + " ";
	}
}</span>

<span style="font-size:18px;">	int capacity;
	HashMap<Integer, Node> map = new HashMap<Integer, Node>();
	Node head = null;
	Node end = null;
 
	public LRUCacheTest(int capacity) {
		this.capacity = capacity;
	}</span>

“为了能够快速删除最久没有访问的数据项和插入最新的数据项,我们将双向链表连接Cache中的数据项,并且保证链表维持数据项从最近访问到最旧访问的顺序。

每次数据项被查询到时,都将此数据项移动到链表头部(O(1)的时间复杂度)

这样,在进行过多次查找操作后,最近被使用过的内容就向链表的头移动,而没有被使用的内容就向链表的后面移动。

当需要替换时,链表最后的位置就是最近最少被使用的数据项,我们只需要将最新的数据项放在链表头部,当Cache满时,淘汰链表最后的位置就是了。 ”

解决了LRU的特性,现在考虑下算法的时间复杂度。为了能减少整个数据结构的时间复杂度,就要减少查找的时间复杂度,所以这里利用HashMap来做,这样时间复杂度就是O(1)。

所以对于本题来说:

get(key): 如果cache中不存在要get的值,返回-1;如果cache中存在要找的值,返回其值并将其在原链表中删除,然后将其插入作为头结点。

public int get(int key) {
if (map.containsKey(key)) {
Node n = map.get(key);
remove(n);
setHead(n);
printNodes(“get”);
return n.value;
}
printNodes(“get”);
return -1;
}

<font color =red>set(key,value):当set的key值已经存在,就更新其value, 将其在原链表中删除,然后将其作为头结点;当set的key值不存在,就新建一个node,如果当前len<capacity,就将其加入hashmap中,并将其作为头结点,更新len长度,否则,删除链表最后一个node,再将其放入hashmap并作为头结点,但len不更新。</font>
```java
<span style="font-size:18px;">	public void set(int key, int value) {
		if (map.containsKey(key)) {
			Node old = map.get(key);
			old.value = value;
			remove(old);
			setHead(old);
		} else {
			Node created = new Node(key, value);
			if (map.size() >= capacity) {
				map.remove(end.key);
				remove(end);
				setHead(created);
 
			} else {
				setHead(created);
			}
 
			map.put(key, created);
		}
		printNodes("set");
	}</span>

原则就是:每当访问链表时都更新链表节点。

最后附上完整源代码及输出结果如下:
注意:1.HashMap中存放的是key,和Node
2.LinkedList中存放的是Node
3.最容易遗忘的是set方法当超出缓存的时候的处理:不仅需要删除在链表中的最后一个元素,同时还要删除在HashMap中对应的结点。。

<span style="font-size:18px;">import java.util.HashMap;
import java.util.Hashtable;
 
/*
 * 权兴权意-2016.9.30
 * 实现一个LRU Cache。要求查询和插入都在O(1) 时间内完成。双向链表+HashMap
 */
 
public class LRUCacheTest {
 
	int capacity;
	HashMap<Integer, Node> map = new HashMap<Integer, Node>();
	Node head = null;
	Node end = null;
 
	public LRUCacheTest(int capacity) {
		this.capacity = capacity;
	}
 
	public int get(int key) {
		if (map.containsKey(key)) {
			Node n = map.get(key);
			remove(n);
			setHead(n);
			printNodes("get");
			return n.value;
		}
		printNodes("get");
		return -1;
	}
 
	public void remove(Node n) {
		if (n.pre != null) {
			n.pre.next = n.next;
		} else {
			head = n.next;
		}
 
		if (n.next != null) {
			n.next.pre = n.pre;
		} else {
			end = n.pre;
		}
 
	}
 
	public void setHead(Node n) {
		n.next = head;
		n.pre = null;
 
		if (head != null)
			head.pre = n;
 
		head = n;
 
		if (end == null)
			end = head;
	}
 
	public void set(int key, int value) {
		if (map.containsKey(key)) {
			Node old = map.get(key);
			old.value = value;
			remove(old);
			setHead(old);
		} else {
			Node created = new Node(key, value);
			if (map.size() >= capacity) {
				map.remove(end.key);
				remove(end);
				setHead(created);
 
			} else {
				setHead(created);
			}
 
			map.put(key, created);
		}
		printNodes("set");
	}
 
	public void printNodes(String explain) {
 
		System.out.print(explain + ":" + head.toString());
		Node node = head.next;
		while (node != null) {
			System.out.print(node.toString());
			node = node.next;
		}
		System.out.println();
	}
 
	public static void main(String[] args) {
		LRUCacheTest lruCacheTest = new LRUCacheTest(5);
		lruCacheTest.set(1, 1);
		lruCacheTest.set(2, 2);
		lruCacheTest.set(3, 3);
		lruCacheTest.set(4, 4);
		lruCacheTest.set(5, 5);
		System.out.println("lruCacheTest.get(1):" + lruCacheTest.get(1));
		lruCacheTest.set(6, 6);
		System.out.println("lruCacheTest.get(2):" + lruCacheTest.get(2));
	}
 
}
 
class Node {
	int key;
	int value;
	Node pre;
	Node next;
 
	public Node(int key, int value) {
		this.key = key;
		this.value = value;
	}
	
	@Override
	public String toString() {
		return this.key + "-" + this.value + " ";
	}
}</span>

输出结果:

set:1-1 
set:2-2 1-1 
set:3-3 2-2 1-1 
set:4-4 3-3 2-2 1-1 
set:5-5 4-4 3-3 2-2 1-1 
get:1-1 5-5 4-4 3-3 2-2 
lruCacheTest.get(1):1
set:6-6 1-1 5-5 4-4 3-3 
get:6-6 1-1 5-5 4-4 3-3 
lruCacheTest.get(2):-1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值