您的位置:首页 > 其它

Leetcode: LRU Cache 解题报告

2014-11-21 17:44 405 查看

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.

SOLUTION 1:

利用了JAVA 自带的LinkedHashMap ,其实这相当于作弊了,面试官不太可能会过。但是我们仍然可以练习一下如何使用LinkedHashMap.

同学们可以参考一下它的官方文档:

https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html#LinkedHashMap(int)

1. OverRide removeEldestEntry 函数,在Size达到最大值最,删除最长时间未访问的节点。

protected boolean removeEldestEntry(Map.Entry eldest) {

return size() > capacity;

}

2. 在Get/ Set的时候,都更新节点,即删除之,再添加之,这样它会作为最新的节点加到双向链表中。

package Algorithms.hash;

import java.util.HashMap;

public class LRUCache {
private class DLink {
DLink pre;
DLink next;
int val;
int key;
DLink(int key, int val) {
this.val = val;
this.key = key;
pre = null;
next = null;
}
}

HashMap<Integer, DLink> map;

DLink head;
DLink tail;

int capacity;

public void removeFist() {
removeNode(head.next);
}

public void removeNode(DLink node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}

// add a node to the tail.
public void addToTail(DLink node) {
tail.pre.next = node;

node.pre = tail.pre;
node.next = tail;

tail.pre = node;
}

public LRUCache(int capacity) {
map = new HashMap<Integer, DLink>();

// two dummy nodes. In that case, we can deal with them more conviencely.
head = new DLink(-1, -1);
tail = new DLink(-1, -1);
head.next = tail;
tail.pre = head;

this.capacity = capacity;
}

public int get(int key) {
if (map.get(key) == null) {
return -1;
}

// update the node.
DLink node = map.get(key);
removeNode(node);
addToTail(node);

return node.val;
}

public void set(int key, int value) {
DLink node = map.get(key);
if (node == null) {
// create a node and add the key-node pair into the map.
node = new DLink(key, value);
map.put(key, node);
} else {
// update the value of the node.
node.val = value;
removeNode(node);
}

addToTail(node);

// if the LRU is full, just remove a node.
if (map.size() > capacity) {
map.remove(head.next.key);
removeFist();
}
}
}


View Code

请移步至主页君的GITHUB代码:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/LRUCache.java

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/LRUCache2.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: