博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 146: LRU Cache
阅读量:7262 次
发布时间:2019-06-29

本文共 1913 字,大约阅读时间需要 6 分钟。

class LRUCache {    private int _capacity;    private int _currentSize;    private Map
nodeMap; private Node head; private Node tail; class Node { public int key; public int value; public Node next; public Node prev; public Node(int k, int v) { key = k; value = v; } } public LRUCache(int capacity) { _capacity = capacity; _currentSize = 0; head = new Node(0, 0); tail = new Node(0, 0); tail.prev = head; head.next = tail; nodeMap = new HashMap<>(); } public int get(int key) { if (!nodeMap.containsKey(key)) { return -1; } moveNode(nodeMap.get(key)); return nodeMap.get(key).value; } public void put(int key, int value) { if (!nodeMap.containsKey(key)) { if (_currentSize == _capacity) { nodeMap.remove(tail.prev.key); tail = tail.prev; tail.next = null; _currentSize--; } Node current = new Node(key, value); current.next = head.next; current.next.prev = current; current.prev = head; head.next = current; nodeMap.put(key, current); _currentSize++; } else { moveNode(nodeMap.get(key)); nodeMap.get(key).value = value; } } private void moveNode(Node current) { current.next.prev = current.prev; current.prev.next= current.next; current.next = head.next; head.next.prev = current; head.next = current; current.prev = head; }}/** * 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); */

 

转载于:https://www.cnblogs.com/shuashuashua/p/7443132.html

你可能感兴趣的文章
struts:div
查看>>
使用Lambda Expressions列出某数值范围中的偶数
查看>>
开始学习Python
查看>>
如何理解我们的记忆?
查看>>
NYOJ242计算球体积
查看>>
Eclipse中SVN的安装步骤(两种)和用法
查看>>
php 生成下载连接
查看>>
手机号ID开关星号(*)
查看>>
java数据类型
查看>>
ubuntu 16.04 tmux
查看>>
ABP框架 - Swagger UI 集成
查看>>
索引排序
查看>>
input onchange事件
查看>>
Laravel Homestead 离线安装
查看>>
换行符java去除字符串中的空格、回车、换行符、制表符
查看>>
杀人游戏系列 之二
查看>>
正则表达式初学笔记
查看>>
Kruskal算法模拟讲解
查看>>
Summary: rand5构造rand7
查看>>
MySQL存储过程中判断形参是否为空null
查看>>