LRU算法&&LeetCode解题报告
题目
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
思路
原理是:
- 双向链表根据每一个节点近期被訪问的时间有序存储,近期被訪问的节点存储在表头,近期没有被訪问的节点存储的表尾,存储根据是由于:近期被訪问的节点在接下来的一段时间仍有非常大的概率被再次訪问到。
- 哈希表的作用是用来提高查找效率,假设不使用哈希表。则查找一个节点的时间复杂度是O(n)。而使用了哈希表,则每一个节点的查找时间复杂度为O(1)。
- 依据键值查找hashmap,假设没找到直接返回-1
- 若找到相应节点node,则将其插入到双向链表表头
- 返回node的value值
- 依据键值查找hashmap。假设找到。则直接将该节点移到表头就可以
- 假设没有找到。首先推断当前Cache是否已满
- 假设已满,则删除表尾节点
- 将新节点插入到表头
AC代码
import java.util.HashMap;
public class LRUCache {
private HashMap<Integer, DoubleListNode> mHashMap;
private DoubleListNode head;
private DoubleListNode tail;
private int capacity;
private int currentsize;
public LRUCache(int capacity) {
this.capacity = capacity;
this.currentsize = 0;
this.mHashMap = new HashMap<Integer, DoubleListNode>();
this.head = this.tail = null;
}
public int get(int key) {
if (mHashMap.containsKey(key)) {
DoubleListNode tNode = mHashMap.get(key);
if (tNode == tail) {
if (currentsize > 1) {
removeNodeFromTail();
moveNodeToHead(tNode);
}
} else if (tNode == head) {
// do nothing
} else {
tNode.pre.next = tNode.next;
tNode.next.pre = tNode.pre;
moveNodeToHead(tNode);
}
return mHashMap.get(key).value;
} else {
return -1;
}
}
private void removeNodeFromTail() {
tail = tail.pre;
if (tail != null) {
tail.next = null;
}
}
private void moveNodeToHead(DoubleListNode node) {
head.pre = node;
node.next = head;
node.pre = null;
head = node;
}
public void set(int key, int value) {
if (mHashMap.containsKey(key)) {
// 更新HashMap中相应的值,并将key相应的Node移至队头
DoubleListNode tNode = mHashMap.get(key);
tNode.value = value;
if (tNode == tail) {
if (currentsize > 1) {
removeNodeFromTail();
moveNodeToHead(tNode);
}
} else if (tNode == head) {
// do nothing
} else {
tNode.pre.next = tNode.next;
tNode.next.pre = tNode.pre;
moveNodeToHead(tNode);
}
mHashMap.put(key, tNode);
} else {
DoubleListNode node = new DoubleListNode(key, value);
mHashMap.put(key, node);
if (currentsize == 0) {
head = tail = node;
currentsize += 1;
} else if (currentsize < capacity) {
moveNodeToHead(node);
currentsize += 1;
} else {
// 删除tail节点。而且添加一个head节点
mHashMap.remove(tail.key);
removeNodeFromTail();
// 添加头节点
moveNodeToHead(node);
}
}
}
public static void main(String[] args) {
LRUCache lruCache = new LRUCache(1);
lruCache.set(2, 1);
System.out.println(lruCache.get(2));
lruCache.set(3, 2);
System.out.println(lruCache.get(2));
System.out.println(lruCache.get(3));
}
private static class DoubleListNode {
public DoubleListNode pre;
public DoubleListNode next;
public int key;
public int value;
public DoubleListNode(int key, int value) {
this.key = key;
this.value = value;
this.pre = this.next = null;
}
}
}
LRU算法&&LeetCode解题报告的更多相关文章
- leetcode解题报告(2):Remove Duplicates from Sorted ArrayII
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...
- 2021字节跳动校招秋招算法面试真题解题报告--leetcode206 反转链表,内含7种语言答案
206.反转链表 1.题目描述 反转一个单链表. 示例: 输入: 1->2->3->4->5->NULL输出: 5->4->3->2->1-> ...
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...
- 2021字节跳动校招秋招算法面试真题解题报告--leetcode19 删除链表的倒数第 n 个结点,内含7种语言答案
2021字节跳动校招秋招算法面试真题解题报告--leetcode19 删除链表的倒数第 n 个结点,内含7种语言答案 1.题目描述 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点. ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
- LeetCode解题报告:LRU Cache
LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should suppo ...
- LeetCode解题报告—— Search in Rotated Sorted Array & Search for a Range & Valid Sudoku
1. Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated(轮流,循环) at so ...
- LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum
1. 1-bit and 2-bit Characters We have two special characters. The first character can be represented ...
- leetCode解题报告5道题(六)
题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest s ...
随机推荐
- Marsonry
前言 1 MagicNumber -> autoresizingMask -> autolayout 以上是纯手写代码所经历的关于页面布局的三个时期 在iphone1-iphone3gs时 ...
- java service
http://www.regexlab.com/zh/jar2exe/demo1.htm http://www.zhangxinxu.com/wordpress/?p=1058 http://www. ...
- Android 模拟登陆 保存密码(信息)到手机中 文件信息读取
package com.wuyou.login; import java.io.IOException; import java.util.Map; import android.app.Activi ...
- win10全系列官方MSDN原版系统安装密钥、版本区别、镜像下载地址与激活教程
微软发布win10正式版已经过去几天了,相信很多同学都心情高涨的装上了期待已久的win10系统,但也有很多同学面对win10系统的众多版本感到一脸茫然,的确,微软在win10系统版本上的划分确实有点多 ...
- Android Animation初识
3.0以前,android支持两种动画模式,tween animation,frame animation,在android3.0中又引入了一个新的动画系统:property animation,这三 ...
- Android 写文件到手机
1)// 在手机中创建文件 FileOutputStream phone_outStream =this.openFileOutput("1.txt", Context.MODE_ ...
- bzoj1444
显然自动机上高斯消元根据AC自动机上的转移可以列出一系列方程但这个样的方程解出来全0是一组解说明有线性组合的情况考虑除非没人能赢,否则每个人赢的概率和为1那么我们只要把原来的第一个方程换成这个即可 . ...
- Apache 'mod_accounting'模块SQL注入漏洞(CVE-2013-5697)
漏洞版本: mod_accounting 0.5 漏洞描述: BUGTRAQ ID: 62677 CVE ID: CVE-2013-5697 mod_accounting是Apache 1.3.x上的 ...
- 【转】virtualbox 4.08安装虚机Ubuntu11.04增强功能失败解决方法
原文网址:http://fuliang.iteye.com/blog/1102998 在笔记本安装Ubuntu11.04增强功能失败 引用 fuliang@fuliang-VirtualBox:~$ ...
- 系统交易策略 hylt
最令我尴尬的事情,莫过于很多朋友来到网站,不知道我说的是什么.大多数人以为鬼仆是推销软件的.其实这里理解是错的,特别是一些软件制作与经销商,更出 于推销的目的,故意夸大产品性能,模糊交易系统与一般行情 ...