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 ...
随机推荐
- thinkpad t530 centos 6.4 有线网卡 设置
由于新装的系统没有安装网卡驱动,各大厂商的标准又不一样,有的电脑在linux下不用安装无线网卡驱动,而很不幸,我的电脑是ret的网卡,只能自行安装,在安装无线网卡的过程中使用到了chkconfig的命 ...
- poj 2411 Mondriaan's Dream_状态压缩dp
题意:给我们1*2的骨牌,问我们一个n*m的棋盘有多少种放满的方案. 思路: 状态压缩不懂看,http://blog.csdn.net/neng18/article/details/18425765 ...
- UITextField输入长度限制
[_yourTextField addTarget:self action:@selector(eventEditingChange:) forControlEvents:UIControlEvent ...
- 如何在cmd窗口启动Tomcat
平时,一般使用tomcat/bin/startup.bat目录在windows环境启动Tomcat,或者使用IDE配置后启动. 下面来简单介绍下如果在cmd窗口直接输入命令启动Tomcat: 1.将t ...
- ASP.NET中时间的绑定和格式化
1.Eval和Bind的区别 绑定表达式 <%# Eval("字段名") %> <%# Bind("字段名") %> 区别 1.e ...
- Ant命令行操作
Ant命令行操作 Ant构建文件可以将项目编译,打包,測试,它是Apache软件基金会jakarta文件夹中的一个子项目,具有跨平台性,操作简单,并且非常easy上手. 关于Ant执行,能够在项目中找 ...
- 从零开始学C++之STL(七):剩下5种算法代码分析与使用示例(remove 、rotate 、sort、lower_bound、accumulate)
一.移除性算法 (remove) C++ Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ...
- Android开发 ADB server didn't ACK, failed to start daemon解决方案
有时候在打开ddms的时候,会看到adb会报如题的错误,解决方案是打开任务管理器,(ctrl+shift+esc),然后关掉adb.exe的进程,重启eclipse就ok了. 还有许多无良商家开发的垃 ...
- Https协议简析及中间人攻击原理
1.基础知识 1.1 对称加密算法 对称加密算法的特点是加密密钥和解密密钥是同一把密钥K,且加解密速度快,典型的对称加密算法有DES.AES等 ...
- HTML与CSS入门——第二章 发布Web内容
知识点: 1.使用文本编辑器创建一个基本的HTML文件的方法 2.使用FTP将文件传送到你的Web服务器的方法 3.文件在Web服务器上应该存储的位置 4.在没有Web服务器的情况下分发Web内容的方 ...