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 ...
随机推荐
- 【POJ1003】Hangover(二分搜索)
直接用库函数二分即可. #include <iostream> #include <cstring> #include <cstdlib> #include < ...
- JSplitPane详解
摘自http://blog.163.com/xiexueyong1987@126/blog/static/1262673422010102711295541/ JSplitPane详解 pasting ...
- ListView之SimpleAdapter
SimpleAdapter是安卓内置的适配器,本文展示的是listview的子项为{图片,文件}组合 如下图所示: 具体代码: SimpleAdapter_test.java /* ListView ...
- 常用JS代码整理
1: function request(paras) { 2: var url = location.href; 3: var paraString = url.substring(url.index ...
- 大到可以小说的Y组合子(二)
问:上一回,你在最后曾提到"抽象性不足",这话怎么说? 答:试想,如果现在需要实现一个其它的递归(比如:Fibonacci),就必须把之前的模式从头套一遍,然后通过fib_make ...
- sqlserver 执行远程数据库代码
1.启用Ad Hoc Distributed Queries: exec sp_configure 'show advanced options',1reconfigureexec sp_config ...
- 空合并操作符??(C#)
??二元操作符在对first??second求值时,大致会经历以下步骤: 1)对first进行求值: 2)如果结果非空,则该结果就是整个表达式的结果: 3)否则求second的值,其结果作为整个表达式 ...
- struts2 注解方式
struts2扫描方法: 扫描其位于包的命名注解的类 “struts, struts2, action 或 actions“. 接着,扫描相匹配下列任一条件的文件: 实例了 com.opensymph ...
- uvA Flooded!
Description To enable homebuyers to estimate the cost of flood insurance, a real-estate firm provide ...
- 对boost::shared_from_this的进一步封装
对boost::shared_from_this的进一步封装 熟悉异步编程的同学可能会对boost::shared_from_this有所了解.我们在传入回调的时候,通常会想要其带上当前类对象的上下文 ...