LeetCode刷题篇——LRU缓存

LRU缓存

题目

实现 LRUCache 类:

  • LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
  • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
  • void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

来源:力扣(LeetCode)
链接

思路

维护一个双向链表和哈希表,哈希表存放键和对应的链表结点,双向链表的头为最久未使用的值,尾为最近使用的值,故去掉最久未使用的值只需移除链表头结点;更新最近使用的值只需将对应结点移到链表尾

class LRUCache {
	class Node {
		int key;
		int value;
		Node last;
		Node next;
		Node() {};
		Node(int key, int value) {
			this.key = key;
			this.value = value;
		}
	}

	int capacity; // 容量
	HashMap<Integer, Node> map; 
	Node head; // 双向链表头
	Node tail; // 双向链表尾

	LRUCache(int cap) {
		capacity = cap;
		map = new HashMap<>();
		head = null;
		tail = null;
	}

	public int get(int key) {
		if (!map.containsKey(key)) {
			return -1;
		} else {
			Node node = map.get(key);
			moveNodeToTail(node);
			return node.value;
		}
	}

	public void put(int key, int value) {
		if (map.containsKey(key)) {
			Node node = map.get(key);
			node.value = value;
      		moveNodeToTail(node);
		} else {
			Node newNode = new Node(key, value);
			map.put(key, newNode);
			addNode(newNode);
			if (map.size() > capacity) { // 检查是否超出容量,若超出则移除链表头结点
				Node head = removeHead();
				map.remove(head.key);
			}
		}
	}

	public void addNode(Node node) {
		if (node == null) {
			return;
		}
		// 若链表中无结点,则将头尾都指向新结点;否则将新结点挂在尾部
		if (head == null) {
			head = node;
			tail = node;
		} else {
			tail.next = node;
			node.last = tail;
			tail = node;
		}
	}

	public void moveNodeToTail(Node node) {
		if (node == null || head == tail || node == tail) { // 若链表只有一个结点,或者当前结点就是尾结点,直接return即可
			return;
		}
		if (node == head) {
			head = node.next;
			head.last = null;
		} else {
			node.last.next = node.next;
			node.next.last = node.last;
		}
		tail.next = node;
		node.last = tail;
		node.next = null;
		tail = node;

	}

	public Node removeHead() {
		if (head == null) {
			return null;
		}
		Node res = head;
		if (head == tail) {
			head = null;
			tail = null;
		} else {
			head = res.next;
			res.next = null;
			head.last = null;
		}
		return res;
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值