数据结构与算法-练习打卡day16(LRU 缓存)

数据结构与算法-练习打卡day16

问题:

题目地址,点我
在这里插入图片描述

解题:

分析:需要对最近使用的操作进行排序,需要判断缓存最大值,但是要注意若对一个值进行多次操作只能有一条记录;至少有一个链表用于存储对值的操作,方便去除队尾,有一个map对值进行操作,用于随机,LinkedHashMap是个不错的选择

	class LRUCache {

		private int maxSize;
		private LinkedHashMap<Integer, Integer> hashMap;

		public LRUCache(int capacity) {
			this.maxSize = capacity;
			this.hashMap = new LinkedHashMap<>(capacity);
		}

		public int get(int key) {
			// 判断是否包含
			if (!hashMap.containsKey(key)) {
				return -1;
			}
			// 调用get的就要改变顺序
			Integer value = hashMap.remove(key);
			hashMap.put(key, value);
			return value;
		}

		public void put(int key, int value) {
			// 判断是否是已经包含的
			if (hashMap.containsKey(key)) {
				// 先从链表中移除
				hashMap.remove(key);
				// 判断是否已经到达临界值
			} else if (hashMap.size() >= maxSize) {
				Integer firstKey = hashMap.keySet().iterator().next();
				hashMap.remove(firstKey);
			}
			// 添加到链表的末尾
			hashMap.put(key, value);
		}
	}
/**
 * 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);
 */

性能:

目前的get和put方法执行的步骤还是比较多的,比较慢
在这里插入图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值