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.

SOLUTION 1:

利用了JAVA 自带的LinkedHashMap ,其实这相当于作弊了,面试官不太可能会过。但是我们仍然可以练习一下如何使用LinkedHashMap.

同学们可以参考一下它的官方文档:

https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html#LinkedHashMap(int)

1. OverRide removeEldestEntry 函数,在Size达到最大值最,删除最长时间未访问的节点。

protected boolean removeEldestEntry(Map.Entry eldest) {

return size() > capacity;

}

2. 在Get/ Set的时候,都更新节点,即删除之,再添加之,这样它会作为最新的节点加到双向链表中。

 package Algorithms.hash;

 import java.util.LinkedHashMap;
import java.util.Map; public class LRUCache2 {
public static void main(String[] strs) {
LRUCache2 lrc2 = new LRUCache2();
lrc2.set(,);
lrc2.set(,);
lrc2.set(,);
lrc2.set(,); System.out.println(lrc2.get());
} LinkedHashMap<Integer, Integer> map;
int capacity; public LRUCache2(final int capacity) {
// create a map.
map = new LinkedHashMap<Integer, Integer>(capacity) {
/**
*
*/
private static final long serialVersionUID = 1L; protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
};
this.capacity = capacity;
} public int get(int key) {
Integer ret = map.get(key);
if (ret == null) {
return -;
} else {
map.remove(key);
map.put(key, ret);
} return ret;
} public void set(int key, int value) {
map.remove(key);
map.put(key, value);
}
}

SOLUTION 2:

使用 HashMap+ 双向链表实现:

1. 如果需要移除老的节点,我们从头节点移除。

2. 如果某个节点被访问(SET/GET),将其移除并挂在双向链表的结尾。

3. 链表满了后,我们删除头节点。

4. 最近访问的节点在链尾。最久被访问的节点在链头。

 package Algorithms.hash;

 import java.util.HashMap;

 public class LRUCache {
private class DLink {
DLink pre;
DLink next;
int val;
int key;
DLink(int key, int val) {
this.val = val;
this.key = key;
pre = null;
next = null;
}
} HashMap<Integer, DLink> map; DLink head;
DLink tail; int capacity; public void removeFist() {
removeNode(head.next);
} public void removeNode(DLink node) {
node.pre.next = node.next;
node.next.pre = node.pre;
} // add a node to the tail.
public void addToTail(DLink node) {
tail.pre.next = node; node.pre = tail.pre;
node.next = tail; tail.pre = node;
} public LRUCache(int capacity) {
map = new HashMap<Integer, DLink>(); // two dummy nodes. In that case, we can deal with them more conviencely.
head = new DLink(-1, -1);
tail = new DLink(-1, -1);
head.next = tail;
tail.pre = head; this.capacity = capacity;
} public int get(int key) {
if (map.get(key) == null) {
return -1;
} // update the node.
DLink node = map.get(key);
removeNode(node);
addToTail(node); return node.val;
} public void set(int key, int value) {
DLink node = map.get(key);
if (node == null) {
// create a node and add the key-node pair into the map.
node = new DLink(key, value);
map.put(key, node);
} else {
// update the value of the node.
node.val = value;
removeNode(node);
} addToTail(node); // if the LRU is full, just remove a node.
if (map.size() > capacity) {
map.remove(head.next.key);
removeFist();
}
}
}

请移步至主页君的GITHUB代码:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/LRUCache.java

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/LRUCache2.java

Leetcode: LRU Cache 解题报告的更多相关文章

  1. 【LeetCode】146. LRU Cache 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典+双向链表 日期 题目地址:https://le ...

  2. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  3. 【LeetCode】LRU Cache 解决报告

    插话:只写了几个连续的博客,博客排名不再是实际"远在千里之外"该.我们已经进入2一万内. 再接再厉.油! Design and implement a data structure ...

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

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

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

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

  6. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  7. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  8. LeetCode:LRU Cache

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

  9. LeetCode——LRU Cache

    Description: Design and implement a data structure for Least Recently Used (LRU) cache. It should su ...

随机推荐

  1. Linux/shell命令的实际应用——查看Port占用 netstat

    启动1024端口一下,是需要root权限的 该Linux/shell命令主要用于解决: 1.查看某端口是否被占用: 2.查看某端口被哪个进程占用: 3.查看某个进程占用了哪些端口: 比如我tomcat ...

  2. 【svn】Centos搭建svn服务器环境

    1.需求描述 在Centos系统中搭建svn服务器环境 2.搭建过程 2.1 yum安装svn [root@localhost /]# yum install svn  2.2 新建目录存储svn目录 ...

  3. 单机多实例MYSQL主从复制

    今天有时间写写,不然心坎里总有点不爽.单机多实例一直都是屌丝的处事风格... 实验环境 RHEL6.5 172.24.0.130  3306 172.24.0.130  3307 01.本次采用的MY ...

  4. WIFI: N, Legacy and AC

    N选项 N spec allows for 20MHz wide channels similar to previous specs but can also combine two 20MHz c ...

  5. lua入门之二:c/c++ 调用lua及多个函数返回值的获取

    当 Lua 调用 C 函数的时候,使用和 C 调用 Lua 同样类型的栈来交互. C 函数从栈中获取她的參数.调用结束后将返回结果放到栈中.为了区分返回结果和栈中的其它的值,每一个 C 函数还会返回结 ...

  6. 【微信小程序】:评论、回复和删除功能 -- 2017/7/14

    1.理论核心:传参->pid,评论父id需要在wxml页面传递:小程序端和WEB端不同核心:前者操纵数据,后者操纵DOM元素对象 2.不废话,直接代码:wxml <view class=& ...

  7. 【mysql】Innodb三大特性之double write

    1.doublewrite buffer(mysql官方的介绍) InnoDB uses a novel file flush technique called doublewrite. Before ...

  8. 一道SQL题

    原题:大池子博客 给定一个access_time表,它记录了用户每个月访问网站的次数,包括三个域:用户.时间.次数.注意表中可能包含用户在1月份的多条记录. 要求查询用户.月份.月累计.总共累计四项的 ...

  9. 【LeetCode】12. Integer to Roman (2 solutions)

    Integer to Roman Given an integer, convert it to a roman numeral. Input is guaranteed to be within t ...

  10. 使用SoapUI生成WS请求报文

    WSDL地址示例:http://10.1.84.10:8100/webService/common/mail?wsdl   打开SoapUI,创建一个Project,输入wsdl地址就ok. 1.访问 ...