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.

LRU(Least Recently Used 最近最少使用)是内存管理的一种页面置换算法,对于在内存中但又不用的数据块(内存块)叫做LRU,操作系统会根据哪些数据属于LRU而将其移出内存而腾出空间来加载另外的数据。这里采用双向链表加HashMap来实现,cache用双向链表连起来,最近访问的都放在链表的头部,经过几次访问尾部的就是不经常访问到的,如果cache已满,就把链表尾部的记录删除。代码如下:

public class LRUCache {
private int cacheSize;
private CacheNode first = new CacheNode();
private CacheNode last = new CacheNode();
private HashMap<Integer, CacheNode> cache;

public LRUCache(int capacity) {
cacheSize = capacity;
first.prev = last;
last.next = first;
cache = new HashMap<Integer, CacheNode>(capacity);
}

public int get(int key) {
CacheNode node = cache.get(key);
if(node != null) {
moveToHead(node);
return node.value;
} else {
return -1;
}
}

public void set(int key, int value) {
CacheNode node = null;
if(!cache.containsKey(key)) {
if(cache.size() == cacheSize) removeTail();
node = new CacheNode();
node.key = key;
node.value = value;
cache.put(key, node);
} else {
node = cache.get(key);
node.value = value;
}
moveToHead(node);
}

private void moveToHead(CacheNode node) {
if(node.prev != null) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
CacheNode head = first.prev;
first.prev = node;
node.next = first;
node.prev = head;
head.next = node;
}

private void removeTail() {
CacheNode lastNode = last.next;
last.next = last.next.next;
last.next.prev = last;
cache.remove(lastNode.key);
}
}

class CacheNode {
CacheNode prev;
CacheNode next;
int value;
int key;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值