Leetcode 146 LRU Cache
来源:互联网 发布:杨幂赵丽颖谁发展 知乎 编辑:程序博客网 时间:2024/06/02 01:43
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and put
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.put(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.
Follow up:
Could you do both operations in O(1) time complexity?
基本思想在于用双向链表来进行LRU的操作。
public class LRUCache { private class Node{ int key; int value; Node prev; Node next; public Node(int key, int value){ this.key = key; this.value = value; } } Node head; Node tail; int capacity; int size; Map<Integer, Node> map; public LRUCache(int capacity) { head = new Node(0,0); head.next = tail; tail = new Node(0,0); tail.prev = head; this.capacity = capacity; size = 0; map = new HashMap<>(capacity); } public int get(int key) { if(map.containsKey(key)){ Node tmp = map.get(key); tmp.prev.next = tmp.next; tmp.next.prev = tmp.prev; tail.prev.next = tmp; tmp.prev = tail.prev; tmp.next = tail; tail.prev = tmp; return tmp.value; }else{ return -1; } } public void put(int key, int value) { if(!map.containsKey(key)){ if(size == capacity){ int tmpkey = head.next.key; head.next = head.next.next; head.next.prev = head; map.remove(tmpkey); size--; } Node tmp = new Node(key,value); map.put(key,tmp); tail.prev.next = tmp; tmp.prev = tail.prev; tmp.next = tail; tail.prev = tmp; size++; }else{ Node tmp = map.get(key); tmp.value = value; tmp.prev.next = tmp.next; tmp.next.prev = tmp.prev; tail.prev.next = tmp; tmp.prev = tail.prev; tmp.next = tail; tail.prev = tmp; } }}/** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
阅读全文
0 0
- LeetCode: LRU Cache [146]
- LeetCode 146 LRU Cache
- LeetCode(146) LRU Cache
- leetcode || 146、LRU Cache
- leetcode 146: LRU Cache
- LeetCode 146 LRU Cache
- LeetCode -146 LRU Cache
- LeetCode 146 LRU Cache
- Leetcode 146 LRU Cache
- Leetcode 146 LRU Cache 模拟操作系统LRU
- 【Leetcode-hard-146】LRU Cache
- LeetCode LRU 缓存 LRU Cache
- leetcode 146 —— LRU Cache
- solution of LeetCode:146 LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [USACO2.1]城堡 The Castle
- RN学习1——前奏,app插件化和热更新的探索
- tcp协议系列文章(5):select:同步I/O复用
- hdoj 1095
- (转载)Eclipse配置js,html,等的自动提示
- Leetcode 146 LRU Cache
- C#同时播放两首音乐
- pinyin4j的使用
- 磁盘的块大小(Block Size)和扇区大小(Sector Size)
- Android实现PDF预览打印
- Softmax函数加速(Part I)
- Android Service获取当前位置(GPS+基站)
- Android Recovery:功能简介。Recovery模式介绍
- hdoj 1096