Leetcode 146. LRU Cache
来源:互联网 发布:淘宝cosplay服装店 编辑:程序博客网 时间:2024/05/10 16:03
public class LRUCache { // double linked list private class Node { Node prev; Node next; int key; int value; public Node (int key, int value) { this.key = key; this.value = value; this.prev = null; this.next = null; } } private int capacity; private HashMap<Integer, Node> map = new HashMap<Integer, Node>(); private Node head = new Node(-1, -1); private Node tail = new Node(-1, -1); public LRUCache(int capacity) { this.capacity = capacity; tail.prev = head; head.next = tail; } public int get(int key) { if (!map.containsKey(key)) { return -1; } // delete current node from the list and move it to tail Node curr = map.get(key); curr.prev.next = curr.next; curr.next.prev = curr.prev; moveToTail(curr); return map.get(key).value; } public void put(int key, int value) { if (get(key) != -1) { map.get(key).value = value; return; } // remove least recently used node if (map.size() == capacity) { map.remove(head.next.key); head.next = head.next.next; head.next.prev = head; } // insert new node to the tail Node newNode = new Node(key, value); map.put(key, newNode); moveToTail(newNode); } public void moveToTail(Node curr) { curr.prev = tail.prev; tail.prev = curr; curr.prev.next = curr; curr.next = tail; }}
0 0
- 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
- 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
- 喵哈哈村的魔法石
- work with sqlserver
- C、C++按位运算总结
- Lua中的loadfile、dofile、require详解
- 算法时间复杂度
- Leetcode 146. LRU Cache
- 匿名调用
- 应用EF访问SQLite数据
- 牛客网——华为编程题训练1-20
- 日期时间jQuery代码
- LintCode : 尾部的零
- Android上Bitmap文件解析示例
- html+css基础1-body(h,p,img)
- Tomcat端口被占用解决方法: java.net.BindException: Address already in use: JVM_Bind <null>:8082