一、题目
运用你所掌握的数据结构,设计和实现一个 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);
}
}
}