数据结构问题:LRU缓存机制_缓存的数据结构

数据结构问题:LRU缓存机制_缓存的数据结构

编码文章call10242025-10-01 18:47:3910A+A-

一、题目

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。写入数据 put(key, value) - 如果密钥已经存在,则变更其数据值;如果密钥不存在,则插入该组「密钥/数据值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

二、思路

使用HashMap和LinkedList,HashMap用于存储key、value,LinkedList用于处理最近最少使用(将使用的在LinkedList中删除,然后添加到LinkedList的末尾,保证最少使用的在LinkedList的头部)

三、实现

class LRUCache {

private int capacity;

private LinkedList<Integer> list;

private HashMap<Integer, Integer> map;

public LRUCache(int capacity) {

this.capacity = capacity;

list = new LinkedList<>();

map = new HashMap<>();

}

public int get(int key) {

if (map.containsKey(key)) {

list.remove((Integer) key);

list.addLast(key);

return map.get(key);

}

return -1;

}

public void put(int key, int value) {

if (map.containsKey(key)) {

list.remove((Integer) key);

list.addLast(key);

map.put(key, value);

} else {

if (capacity == list.size()) {

map.remove(list.removeFirst());

}

map.put(key,value);

list.addLast(key);

}

}

}


点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4