LRU Cache 解答
Question
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
My first thought is to use a linked list and a hashmap. But remove and add element for linked list is O(n) per step.
So, the final idea is to implement a bi-directional linked list.
For this question, I submitted over 10 times and finally got accepted.
There are many details we need to check.
1. When deleting a node, we should modify both prev and next attributes of its neighbors.
2. Every time when we add a new node, we should check whether it is the first node.
3. When input capacity is 1, we should deal with it separately.
// Construct double list node
class Node {
public Node prev;
public Node next;
private int val;
private int key;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
public void setValue(int val) {
this.val = val;
}
public int getKey() {
return key;
}
public int getValue() {
return val;
}
} public class LRUCache {
private int capacity;
private Map<Integer, Node> map;
private Node head;
private Node tail; public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<Integer, Node>();
} private void moveToHead(Node target) {
// Check whether target is already at head
if (target.prev == null)
return;
// Check whether target is at tail
if (target == tail)
tail = target.prev;
Node prev = target.prev;
Node next = target.next;
if (prev != null)
prev.next = next;
if (next != null)
next.prev = prev; Node oldHead = head;
target.prev = null;
target.next = oldHead;
oldHead.prev = target;
head = target;
} public int get(int key) {
if (!map.containsKey(key))
return -1;
Node current = map.get(key);
// Move found node to head
moveToHead(current);
return current.getValue();
} public void set(int key, int value) {
if (map.containsKey(key)) {
Node current = map.get(key);
current.setValue(value);
// Move found node to head
moveToHead(current); } else {
Node current = new Node(key, value);
// Add new node to map
map.put(key, current); // Check whether map size is bigger than capacity
if (map.size() > capacity) {
// Move farest used element out
Node last = tail;
map.remove(last.getKey());
// Remove from list
if (map.size() == 1) {
head = current;
tail = current;
} else {
Node oldHead = head;
current.next = oldHead;
oldHead.prev = current;
head = current;
tail = tail.prev;
tail.next = null;
} } else {
// Add new node to list
if (map.size() == 1) {
head = current;
tail = current;
} else {
Node oldHead = head;
current.next = oldHead;
oldHead.prev = current;
head = current;
}
}
}
}
}
LRU Cache 解答的更多相关文章
- [LeetCode]LRU Cache有个问题,求大神解答【已解决】
题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...
- [LeetCode] LRU Cache 最近最少使用页面置换缓存器
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- 【leetcode】LRU Cache
题目简述: Design and implement a data structure for Least Recently Used (LRU) cache. It should support t ...
- LeetCode:LRU Cache
题目大意:设计一个用于LRU cache算法的数据结构. 题目链接.关于LRU的基本知识可参考here 分析:为了保持cache的性能,使查找,插入,删除都有较高的性能,我们使用双向链表(std::l ...
- LRU Cache实现
最近在看Leveldb源码,里面用到LRU(Least Recently Used)缓存,所以自己动手来实现一下.LRU Cache通常实现方式为Hash Map + Double Linked Li ...
- 【leetcode】LRU Cache(hard)★
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- [LintCode] LRU Cache 缓存器
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- LRU Cache [LeetCode]
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- 43. Merge Sorted Array && LRU Cache
Merge Sorted Array OJ: https://oj.leetcode.com/problems/merge-sorted-array/ Given two sorted integer ...
随机推荐
- ps&&/proc/pid/xxx
ps 如果想看一个进程的启动时间,可以用lstart来看 [root@jiangyi02.sqa.zmf /home/ahao.mah] #ps -eo pid,lstart,etime,cmd |g ...
- hdu 5335 Walk Out(bfs+寻找路径)
Problem Description In an n∗m maze, the right-bottom corner or a written on it. An explorer gets los ...
- H Language Blueprint
H Language Blueprint I will design the H language in the very-soon future, it will be like: 1- a scr ...
- 高仿拉手网底部菜单实现FragmentActivity+Fragment+RadioGroup
先把欢迎页和引导页的代码上传了http://download.csdn.net/detail/u013134391/7183787不要积分的. 底部菜单条实如今4.0曾经都是用tabhost.如今基本 ...
- 笔记--cocos2d-x 3.0 环境搭建
一.下载资源工具 1.下载cocos2d-x 3.0 官网地址:http://www.cocos2d-x.org/filedown/cocos2d-x-3.0-cn 2.下载VS2012 地址网上搜 ...
- Android应用程序键盘(Keyboard)消息处理机制分析
在Android系统中,键盘按键事件是由WindowManagerService服务来管理的,然后再以消息的形 式来分发给应用程序处理,不过和普通消息不一样,它是由硬件中断触发的:在上一篇文章< ...
- Codeforces 466 E. Information Graph
并查集.... E. Information Graph time limit per test 1 second memory limit per test 512 megabytes input ...
- mvc 5 的过滤器和webapi 过滤器 对应实现的action过滤器区别
asp.net webapi Action过滤器实现这个: #region 程序集 System.Web.Http, Version=5.2.3.0, Culture=neutral, Publi ...
- CLR via C# - GC
//像背书一样,记录下吧 1.CLR分配资源 托管堆上维护着一个指针NextObjPtr.该指针表示下一个新建对象在托管堆上的位置.C#的new Object会产生IL newobj指令,NextOb ...
- CSS兼容性常见问题总结
DIV+CSS设计IE6.IE7.FF 兼容性 DIV+CSS网页布局这是一种趋势,我也开始顺应这股趋势了,不过在使用DIV+CSS网站设计的时候,应该注意css样式兼容不同浏览器问题,特别是对完全使 ...