LeetCode LRU Cache (Java实现)
来源:互联网 发布:全军战备值班部队 知乎 编辑:程序博客网 时间:2024/05/20 12:48
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.
参考自两篇博客
http://blog.csdn.net/beiyeqingteng/article/details/7010411
http://gogole.iteye.com/blog/692103
值得一提的是LruCache在Android平台下做图片的缓存非常有效,关于LruCache的官方实现可以参考
http://blog.csdn.net/linghu_java/article/details/8574102
其实 LruCache 也没做什么特别的东西,它不过是给 LinkedHashMap 包了一层而已,真正实现 lru 算法的还是LinkedHashMap
在面试的时候面试官可能不喜欢你用LinkedHashMap实现,所以以下由双链表+hashtable实现
import java.util.Hashtable;public class LRUCache { int capacity; int size; CacheNode first; CacheNode last; Hashtable<Integer, CacheNode> nodes = new Hashtable<Integer, CacheNode>(); class CacheNode{ CacheNode prev; CacheNode next; int key; int value; } public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { CacheNode node = nodes.get(key); if (node == null) return -1; moveToHead(node); return node.value; } public void set(int key, int value) { CacheNode node = nodes.get(key); if (node == null){ if (size >= capacity){ if (last != null){ nodes.remove(last.key); } removeLast(); }else{ ++size; } node = new CacheNode(); } node.key = key; node.value = value; moveToHead(node); nodes.put(key, node); } private void removeLast(){ if (last != null){ if (last.prev != null){ last.prev.next = null; }else{ first = null; } last = last.prev; } } private void moveToHead(CacheNode node){ if (node == first) return; if (node.prev != null) node.prev.next = node.next; if (node.next != null) node.next.prev = node.prev; if (last == node) last = node.prev; if (first != null){ first.prev = node; } node.next = first; first = node; node.prev = null; if (last == null) last = first; }}
- LeetCode LRU Cache (Java实现)
- [Leetcode] LRU Cache (Java)
- [leetCode] LRU Cache (Java)
- LeetCode|LRU Cache-java
- LRU cache实现 (Java)
- LRU cache实现 (Java)
- [LeetCode] 146. LRU Cache java
- LRU cache实现 -Java 转
- LRU Cache算法实现(leetcode)
- LeetCode LRU 缓存 LRU Cache
- java实现简单的LRU Cache
- 设计并实现一个LRU Cache (java)
- java如何实现一个LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- JVM学习笔记
- WinXP下打造自己的linux 0.11简易编译环境(原创)
- remove element
- 【二分图|最大匹配】POJ-3041 Asteroids(匈牙利算法dfs、bfs版)
- iOS 在TabViewController中设置Tab Bar,且实现自定义
- LeetCode LRU Cache (Java实现)
- Git代码分支管理在项目中的实践
- 将一组按以下规则排序:第一个数最大,第二个数最小,第三个数是剩下中最大的,第四个数是剩下中最小的,依次类推。
- python面向对象编程
- Install Composer on CentOS
- C语言日期倒计时
- JSP(三)
- OS 通知中心扩展制作入门
- 如何在面试中发现优秀程序员(转)