力扣hot100 LRU 缓存 有序Map

Problem: 146. LRU 缓存

文章目录

  • 思路
  • [💖 Code](#💖 Code)

思路

👨‍🏫 参考题解

👩‍🏫 参考图解

💖 Code

⏰ 两操作 时间复杂度: O ( 1 ) O(1) O(1)

Java 复制代码
class LRUCache
{
	int cap;
	LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>();

	public LRUCache(int capacity)
	{
		this.cap = capacity;// 初始化容量
	}

	public int get(int key)
	{
		if (!cache.containsKey(key))// 缓存不存在返回 -1
			return -1;
		makeRecntly(key);// 更新访问时间
		return cache.get(key);
	}

//	让 key 重新入 缓存 
	private void makeRecntly(int key)
	{
		int val = cache.get(key);
		cache.remove(key);
		cache.put(key, val);
	}

	public void put(int key, int val)
	{
		if (cache.containsKey(key))
		{
			cache.put(key, val);// 更新 cache 的值,已存在则不增加容量
			makeRecntly(key);
			return;
		}
		if (cache.size() >= this.cap)// 其实 == 就要删除旧元素了,先删后加
		{
			// 用迭代器拿出 keySet 中的第一个 key
			int old = cache.keySet().iterator().next();
			cache.remove(old);// 删除最旧的数据
		}
		cache.put(key, val);
	}
}
相关推荐
骑着猪去兜风.1 天前
线段树(二)
数据结构·算法
fengfuyao9851 天前
竞争性自适应重加权算法(CARS)的MATLAB实现
算法
散峰而望1 天前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
leoufung1 天前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
wyhwust1 天前
交换排序法&冒泡排序法& 选择排序法&插入排序的算法步骤
数据结构·算法·排序算法
利刃大大1 天前
【动态规划:背包问题】完全平方数
c++·算法·动态规划·背包问题·完全背包
wyhwust1 天前
数组----插入一个数到有序数列中
java·数据结构·算法
im_AMBER1 天前
Leetcode 59 二分搜索
数据结构·笔记·学习·算法·leetcode
gihigo19981 天前
基于MATLAB的IEEE 14节点系统牛顿-拉夫逊潮流算法实现
开发语言·算法·matlab
leoufung1 天前
LeetCode 61. 旋转链表(Rotate List)题解与思路详解
leetcode·链表·list