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.


题解:用双向链表实现一个LRU cache,这里自定义越靠近链表头的node,在越近的时间使用过。支持两个操作——get和set:

  1. get(key):如果链表中有key对应的node,返回该node的值,并把node移到链表头部(最近使用过);如果没有,返回-1;
  2. set(key,value):如果链表中已经有key对应的node,修改对应node的值为value(但不需要把这个node放在头结点处);如果链表中没有key对应的node,那么要新建node插入链表中,但此时要看链表是否还有空间。如果没有,就将尾部node(最少使用的node)删除,然后在头部插入新的node。

为了提高查找效率,这里使用一个hashMap存放<key,node>键值对,这样就可以在O(1)的时间判断cache中是否存在对应的key。

代码如下:

 public class LRUCache {
private class Node{
int value;
int key;
Node before;
Node after;
public Node(int key,int value){
this.value = value;
this.key = key;
before = null;
after = null;
}
} private int capacity;
private HashMap<Integer, Node> map = new HashMap<Integer,Node>();
private Node headNode = new Node(-1, -1);
private Node tailNode = new Node(-1, -1); public LRUCache(int capacity) {
this.capacity = capacity;
headNode.after = tailNode;
tailNode.before = headNode;
} public void move_to_head(Node current){
current.after = headNode.after;
headNode.after = current;
current.before = headNode;
current.after.before = current;
}
public int get(int key) {
//if we don't have this node
if(!map.containsKey(key))
return -1; //if we have this node, get it and move it to head
Node current = map.get(key);
current.before.after = current.after;
current.after.before = current.before;
move_to_head(current); return map.get(key).value;
} public void set(int key, int value) {
//if we already have this node,just change its value
if(get(key) != -1){
map.get(key).value = value;
return;
} //if we indeed don't have this node, we first check capacity
if(map.size() == capacity){
map.remove(tailNode.before.key);
tailNode.before.before.after = tailNode;
tailNode.before = tailNode.before.before;
} //now we are sure we have space for this new node,put it ahead of the list
Node newNode = new Node(key, value);
map.put(key, newNode);
move_to_head(newNode);
}
}

在实现的时候,还设置了两个node:head和tail,真正的cache数据节点存放在二者之间。

【leetcode刷题笔记】LRU Cache的更多相关文章

  1. LeetCode刷题笔记和想法(C++)

    主要用于记录在LeetCode刷题的过程中学习到的一些思想和自己的想法,希望通过leetcode提升自己的编程素养 :p 高效leetcode刷题小诀窍(这只是目前对我自己而言的小方法,之后会根据自己 ...

  2. 18.9.10 LeetCode刷题笔记

    本人算法还是比较菜的,因此大部分在刷基础题,高手勿喷 选择Python进行刷题,因为坑少,所以不太想用CPP: 1.买股票的最佳时期2 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. ...

  3. LeetCode刷题笔记 - 12. 整数转罗马数字

    学好算法很重要,然后要学好算法,大量的练习是必不可少的,LeetCode是我经常去的一个刷题网站,上面的题目非常详细,各个标签的题目都有,可以整体练习,本公众号后续会带大家做一做上面的算法题. 官方链 ...

  4. Leetcode刷题笔记(双指针)

    1.何为双指针 双指针主要用来遍历数组,两个指针指向不同的元素,从而协同完成任务.我们也可以类比这个概念,推广到多个数组的多个指针. 若两个指针指向同一数组,遍历方向相同且不会相交,可以称之为滑动窗口 ...

  5. LeetCode刷题笔记(1-9)

    LeetCode1-9 本文更多是作为一个习题笔记,没有太多讲解 1.两数之和 题目请点击链接 ↑ 最先想到暴力解法,直接双循环,但是这样复杂度为n平方 public int[] twoSum(int ...

  6. leetcode刷题笔记

    (1)Best Time to Buy and Sell Stock Total Accepted: 10430 Total Submissions: 33800My Submissions Say ...

  7. leetcode刷题笔记08 字符串转整数 (atoi)

    题目描述 实现 atoi,将字符串转为整数. 在找到第一个非空字符之前,需要移除掉字符串中的空格字符.如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即 ...

  8. LeetCode刷题笔记-回溯法-分割回文串

    题目描述: 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回 s 所有可能的分割方案. 示例: 输入: "aab"输出:[ ["aa", ...

  9. leetcode刷题笔记231 2的幂

    题目描述: 给定一个整数,写一个函数来判断它是否是2的幂. 题目分析: 判断一个整数是不是2的幂,可根据二进制来分析.2的幂如2,4,8,等有一个特点: 二进制数首位为1,其他位为0,如2为10,4为 ...

随机推荐

  1. 不使用库函数,编写函数int strcmp(char *source, char *dest) 相等返回0,不等返回-1;

    答案:一. int strcmp(char  *source, char *dest) { /* assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stder ...

  2. python 基础 9.4 游标

    一. 游标是系统为用户开设的一个数据缓冲区,存放SQL语句的执行结果.       用户可以用SQL 语句逐一从游标中获取记录,并赋值给主变量,交由python 进一步处理,一组主变量一次只能存放一条 ...

  3. Eight(经典题,八数码)

    Eight Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Subm ...

  4. EasyDSS直播服务器如何帮助用户解决OBS不能同时同步输出多路直播流到直播平台、CDN平台的限制

    最近有用户突然寻求帮助,大概的意思就是说: 他需要同步将桌面的直播同时RTMP发布到:斗鱼.熊猫TV等等多个平台,但是OBS又只能同时采集并发布推流直播到单一个平台,而且有时候在4G或者网络比较差的情 ...

  5. 微信小程序 入门

    目录结构: app.json  .小程序的全局配置 pages:  当前小程序所有页面路径. window:小程序所有页面的顶部背景颜色,文字颜色定义在这里. tabBar:  设置底部 tab ne ...

  6. linux字符集查看与设置

    linux字符集查看与设置 命令:locale -a   查看本地的字符集        locale -m 查看所有支持的字符集   查看当前默认设置   echo $LANG   记录系统默认使用 ...

  7. 虚拟机 minimal 安装增强包

    在虚拟机下安装了一个centos的minimal镜像,发现增强包不能安装,鼠标不能在虚拟机和物理机间自由切换.不能共享粘贴板,非常是不爽,这里摸索出在centos  minimal OS下安装增强包的 ...

  8. The given 'driver' ] is unknown, Doctrine currently supports only the follo wing drivers: pdo_mysql, pdo_sqlite, pdo_pgsql, pdo_oci, oci8, ibm_db2, pdo

    [Doctrine\DBAL\DBALException]                                                  The given 'driver' ] ...

  9. git入门篇-----本地操作

    一 ,git的简介 1 ,git的历史 概念性的知识,大家百度一下,就会出现好多优秀的文章供参考,这里我就不多说了. 如果不是当年BitMover公司威胁Linux社区,可能现在我们就没有免费而超级好 ...

  10. 常用JQuery设置HTML元素内容

    主要内容: 一.获取内容及属性 二.设置内容及属性 三.添加元素 四.删除元素 五.css()方法 六.寻找祖先及后代 一.获取内容及属性 二.设置内容及属性 相对于获取内容及属性的方式,只需在函数内 ...