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.

details

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 解答的更多相关文章

  1. [LeetCode]LRU Cache有个问题,求大神解答【已解决】

    题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...

  2. [LeetCode] LRU Cache 最近最少使用页面置换缓存器

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  3. 【leetcode】LRU Cache

    题目简述: Design and implement a data structure for Least Recently Used (LRU) cache. It should support t ...

  4. LeetCode:LRU Cache

    题目大意:设计一个用于LRU cache算法的数据结构. 题目链接.关于LRU的基本知识可参考here 分析:为了保持cache的性能,使查找,插入,删除都有较高的性能,我们使用双向链表(std::l ...

  5. LRU Cache实现

    最近在看Leveldb源码,里面用到LRU(Least Recently Used)缓存,所以自己动手来实现一下.LRU Cache通常实现方式为Hash Map + Double Linked Li ...

  6. 【leetcode】LRU Cache(hard)★

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  7. [LintCode] LRU Cache 缓存器

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  8. LRU Cache [LeetCode]

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  9. 43. Merge Sorted Array && LRU Cache

    Merge Sorted Array OJ: https://oj.leetcode.com/problems/merge-sorted-array/ Given two sorted integer ...

随机推荐

  1. MVC 增加统一异常处理机制

    原文地址:http://www.cnblogs.com/leoo2sk/archive/2008/11/05/1326655.html 摘要      本文将对“MVC公告发布系统”的发布公告功能添加 ...

  2. 04747_Java语言程序设计(一)_第6章_图形界面设计(二)

    例6.1声明一个面板子类,面板子类对象有3个选择框. class Panel1 extends JPanel { JCheckBox box1, box2, box3; Panel1() { box1 ...

  3. 雅虎工程师初始化css

    /*css reset code */ /**** 文字大小初始化,使1em=10px *****/ body { font-size:62.5%; } /* for IE/Win */ html&g ...

  4. Handsontable通用方法

    1.clear():清空数据 2.createCol(index,amount,createAutomatically):添加列        index:列索引,amount:添加的列总数,crea ...

  5. All X(思维)

    All X Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Total Subm ...

  6. 怎么实现类似星星闪烁的效果(box-shadow)

    有时候设计希望我们能够在页面实现类似星星闪烁的效果,如图: 我的解决办法是用box-shadow: html <div class="star04 active-blink" ...

  7. dtree基础

    最近用到了dtree来建立树,纠结过好久后,终于有了些门道,下面的总结希望对咪咪们有些帮助: dtree用来建立静态树或者动态树都是很方便的,老外给提供了整个的JS,然后我们只是操心这个树中存放的元素 ...

  8. cookie丢失、登陆自动退出问题解决

    cookie保存在客户端或者内存中,不易丢失.但是在某些情况下会被忽略.在项目过程中遇到过跨域丢失的情况.在VS里面运行的程序,产生的cookie默认是没有domain值的,但是给它设定domain值 ...

  9. baidu地图让多个标注出现在最佳视野

    原文:http://www.cnblogs.com/milkmap/archive/2011/08/23/2150641.html 摘要: “我有一堆标注,不规则的散落在地图的各个地方,我想把它们展示 ...

  10. SQL Server -SET QUOTED_IDENTIFIER

    SET QUOTED_IDENTIFIER ON SQL SERVER的联机丛书的解释: “当 SET QUOTED_IDENTIFIER 为 ON 时,标识符可以由双引号分隔,而文字必须由单引号分隔 ...