LRU缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥已经存在,则变更其数据值;如果密钥不存在,则插入该组「密钥/数据值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?

示例:

LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得密钥 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得密钥 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4

代码:

package test3;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; class Node {
int key;
int val;
Node next;
Node prev; public Node(int key, int val){
this.key = key;
this.val = val;
next = null;
prev = null;
}
} public class LruCache {
private int capacity;
private HashMap<Integer, Node> cacheMap;
private Node head, tail; public LruCache(int capacity) {
this.capacity = capacity;
this.cacheMap = new LinkedHashMap<>();
this.head = new Node(-1, -1);
this.tail = new Node(-1, -1);
head.next = tail;
head.prev = tail;
tail.next = head;
tail.prev = head;
} public int get(int key) {
if(!cacheMap.containsKey(key)) {
return -1;
}
Node node = cacheMap.get(key);
moveToHead(node);
return node.val;
} public void put(int key, int value) {
if (cacheMap.containsKey(key)) {
cacheMap.get(key).val = value;
moveToHead(cacheMap.get(key));
} else {
Node node = new Node(key, value);
if (cacheMap.size() >= this.capacity) {
Node rm = tail.prev;
deleteNode(rm);
cacheMap.remove(rm.key);
}
insertHead(node);
cacheMap.put(key, node);
}
} private void moveToHead(Node node) {
deleteNode(node);
insertHead(node);
} private void insertHead(Node node) {
Node next = head.next;
head.next = node;
node.prev = head;
node.next = next;
next.prev = node;
} private void deleteNode(Node node) {
Node front = node.prev;
Node end = node.next;
front.next = end;
end.prev = front;
} public void printCache() {
StringBuilder sb=new StringBuilder();
sb.append("["); List<String> ls=new ArrayList<String>();
for(int key:cacheMap.keySet()) {
Node value=cacheMap.get(key);
ls.add("("+key+","+value.val+")");
}
sb.append(String.join(",", ls)); sb.append("]");
System.out.println(sb.toString());
} public static void main(String[] args) throws Exception{
LruCache cache=new LruCache(2);
cache.put(1,1);
System.out.print(".....");
cache.printCache();
System.out.println(); cache.put(2,2);
System.out.print(".....");
cache.printCache();
System.out.println(); System.out.print(cache.get(1));
System.out.print(".....");
cache.printCache();
System.out.println(); cache.put(3, 3);
System.out.print(".....");
cache.printCache();
System.out.println(); System.out.print(cache.get(2));
System.out.print(".....");
cache.printCache();
System.out.println(); cache.put(4, 4);
System.out.print(".....");
cache.printCache();
System.out.println(); System.out.print(cache.get(1));
System.out.print(".....");
cache.printCache();
System.out.println(); System.out.print(cache.get(3));
System.out.print(".....");
cache.printCache();
System.out.println(); System.out.print(cache.get(4));
System.out.print(".....");
cache.printCache();
System.out.println();
}
}

输出:

.....[(1,1)]

.....[(1,1),(2,2)]

1.....[(1,1),(2,2)]

.....[(1,1),(3,3)]

-1.....[(1,1),(3,3)]

.....[(3,3),(4,4)]

-1.....[(3,3),(4,4)]

3.....[(3,3),(4,4)]

4.....[(3,3),(4,4)]

--2020年5月11日--

Q200510-03-03 :LRU缓存机制的更多相关文章

  1. [Leetcode]146.LRU缓存机制

    Leetcode难题,题目为: 运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制.它应该支持以下操作: 获取数据 get 和 写入数据 put . 获取数据 get(key ...

  2. Java实现 LeetCode 146 LRU缓存机制

    146. LRU缓存机制 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制.它应该支持以下操作: 获取数据 get 和 写入数据 put . 获取数据 get(key) - ...

  3. 常见面试题之操作系统中的LRU缓存机制实现

    LRU缓存机制,全称Least Recently Used,字面意思就是最近最少使用,是一种缓存淘汰策略.换句话说,LRU机制就是认为最近使用的数据是有用的,很久没用过的数据是无用的,当内存满了就优先 ...

  4. Q200510-03-02: LRU缓存机制

    问题: LRU缓存机制运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制.它应该支持以下操作: 获取数据 get 和 写入数据 put . 获取数据 get(key) - 如果 ...

  5. 力扣 - 146. LRU缓存机制

    目录 题目 思路 代码 复杂度分析 题目 146. LRU缓存机制 思路 利用双链表和HashMap来解题 看到链表题目,我们可以使用头尾结点可以更好进行链表操作和边界判断等 还需要使用size变量来 ...

  6. 146. LRU 缓存机制 + 哈希表 + 自定义双向链表

    146. LRU 缓存机制 LeetCode-146 题目描述 题解分析 java代码 package com.walegarrett.interview; /** * @Author WaleGar ...

  7. 【golang必备算法】 Letecode 146. LRU 缓存机制

    力扣链接:146. LRU 缓存机制 思路:哈希表 + 双向链表 为什么必须要用双向链表? 因为我们需要删除操作.删除一个节点不光要得到该节点本身的指针,也需要操作其前驱节点的指针,而双向链表才能支持 ...

  8. 【力扣】146. LRU缓存机制

    运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制.它应该支持以下操作: 获取数据 get 和 写入数据 put . 获取数据 get(key) - 如果关键字 (key) ...

  9. [Swift]LeetCode146. LRU缓存机制 | LRU Cache

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

随机推荐

  1. CentOS7 安装 SonarQube

    安装 SonarQube 环境 系统 CentOS 7 数据库 postgresql 10 系统配置 查看系统配置 sysctl vm.max_map_count sysctl fs.file-max ...

  2. 新司机的致胜法宝,使用ApexSql Log2018快速恢复数据库被删除的数据

    作为开发人员,误操作数据delete.update.insert是最正常不过的了,比如: 删除忘记加where条件: 查询为了图方便按了F5,但是数据里面夹杂着delete语句. 不管是打着后发动机声 ...

  3. 谁来教我渗透测试——黑客必须掌握的HTML基础(一)

    小伙伴们,好几天不见了,这一周菜鸟小白工作很忙,所以没有每天更新学习内容,但是菜鸟小白的学习是没有停下来的,只是没有时间来整理学习笔记了.现在就将菜鸟小白这两天学习的HTML基础和大家分享,其中还会拿 ...

  4. Catalina 默认使用zsh了,你可习惯

    zsh 成为默认 shell 淘汰掉我的旧MBP换新后,欢天喜地打开Terminal,感觉有点不对,提示符什么时候变成了 %. 查询了一些资料发现,原来在2019年WWDC期间,苹果推出了macOS ...

  5. 字节跳动:[编程题]万万没想到之聪明的编辑 Java

    时间限制:1秒 空间限制:32768K 我叫王大锤,是一家出版社的编辑.我负责校对投稿来的英文稿件,这份工作非常烦人,因为每天都要去修正无数的拼写错误.但是,优秀的人总能在平凡的工作中发现真理.我发现 ...

  6. C#LeetCode刷题之#58-最后一个单词的长度(Length of Last Word)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3927 访问. 给定一个仅包含大小写字母和空格 ' ' 的字符串, ...

  7. golang的树结构三种遍历方式

    package main import "log" type node struct { Item string Left *node Right *node } type bst ...

  8. TCP/IP速记

    目录 网络协议 OSI七层模型和TCP/IP五层模型 TCP/IP五层模型 TCP的三次握手和四次挥手 三次握手进行连接 四次挥手断开连接 TCP连接的特点 TCP是如何保证安全可靠的 UDP连接的特 ...

  9. 三分钟秒懂BIO/NIO/AIO区别?

    首先来举个例子说明吧,假设你想吃一份盖饭: 同步阻塞:你到饭馆点餐,然后在那等着,还要一边喊:好了没啊! 同步非阻塞:在饭馆点完餐,就去遛狗了.不过溜一会儿,就回饭馆喊一声:好了没啊! 异步阻塞:遛狗 ...

  10. vue+leaflet

    1.index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...