虽然,力扣要求是用时间复杂度 O(1) 来解,但是其它方式我感觉也有必要了解,毕竟是一个由浅到深的过程,自己实现一遍总归是好的。因此,我就把五种求解方式,从简单到复杂,都讲一遍。
LFU实现
力扣原题描述如下:
请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。它应该支持以下操作:get 和 put。
get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。
put(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近 最少使用的键。
「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
示例:
LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 去除 key 2
cache.get(2); // 返回 -1 (未找到key 2)
cache.get(3); // 返回 3
cache.put(4, 4); // 去除 key 1
cache.get(1); // 返回 -1 (未找到 key 1)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lfu-cache
就是要求我们设计一个 LFU 算法,根据访问次数(访问频次)大小来判断应该删除哪个元素,get和put操作都会增加访问频次。当访问频次相等时,就判断哪个元素是最久未使用过的,把它删除。
因此,这道题需要考虑两个方面,一个是访问频次,一个是访问时间的先后顺序。
方案一:使用优先队列
思路:
我们可以使用JDK提供的优先队列 PriorityQueue 来实现 。 因为优先队列内部维护了一个二叉堆,即可以保证每次 poll 元素的时候,都可以根据我们的要求,取出当前所有元素的最大值或是最小值。只需要我们的实体类实现 Comparable 接口就可以了。
当 cache 容量不足时,根据访问频次 freq 的大小来删除最小的 freq 。若相等,则删除 index 最小的,因为index是自增的,越大说明越是最近访问过的,越小说明越是很长时间没访问过的元素。
因本质是用二叉堆实现,故时间复杂度为O(logn)。
public class LFUCache4 {
public static void main(String[] args) {
LFUCache4 cache = new LFUCache4(2);
cache.put(1, 1);
cache.put(2, 2);
// 返回 1
System.out.println(cache.get(1));
cache.put(3, 3); // 去除 key 2
// 返回 -1 (未找到key 2)
System.out.println(cache.get(2));
// 返回 3
System.out.println(cache.get(3));
cache.put(4, 4); // 去除 key 1
// 返回 -1 (未找到 key 1)
System.out.println(cache.get(1));
// 返回 3
System.out.println(cache.get(3));
// 返回 4
System.out.println(cache.get(4));
}
//缓存了所有元素的node
Map<Integer,Node> cache;
//优先队列
Queue<Node> queue;
//缓存cache 的容量
int capacity;
//当前缓存的元素个数
int size;
//全局自增
int index = 0;
//初始化
public LFUCache4(int capacity){
this.capacity = capacity;
if(capacity > 0){
queue = new PriorityQueue<>(capacity);
}
cache = new HashMap<>();
}
public int get(int key){
Node node = cache.get(key);
// node不存在,则返回 -1
if(node == null) return -1;
//每访问一次,频次和全局index都自增 1
node.freq++;
node.index = index++;
// 每次都重新remove,再offer是为了让优先队列能够对当前Node重排序
//不然的话,比较的 freq 和 index 就是不准确的
queue.remove(node);
queue.offer(node);
return node.value;
}
public void put(int key, int value){
//容量0,则直接返回
if(capacity == 0) return;
Node node = cache.get(key);
//如果node存在,则更新它的value值
if(node != null){
node.value = value;
node.freq++;
node.index = index++;
queue.remove(node);
queue.offer(node);
}else {
//如果cache满了,则从优先队列中取出一个元素,这个元素一定是频次最小,最久未访问过的元素
if(size == capacity){
cache.remove(queue.poll().key);
//取出元素后,size减 1
size--;
}
//否则,说明可以添加元素,于是创建一个新的node,添加到优先队列中
Node newNode = new Node(key, value, index++);
queue.offer(newNode);
cache.put(key,newNode);
//同时,size加 1
size++;
}
}
//必须实现 Comparable 接口才可用于排序
private class Node implements Comparable<Node>{
int key;
int value;
int freq = 1;
int index;
public Node(){
}
public Node(int key, int value, int index){
this.key = key;
this.value = value;
this.index = index;
}
@Override
public int compareTo(Node o) {
//优先比较频次 freq,频次相同再比较index
int minus = this.freq - o.freq;
return minus == 0? this.index - o.index : minus;
}
}
}
方案二:使用一条双向链表
思路:
只用一条双向链表,来维护频次和时间先后顺序。那么,可以这样想。把频次 freq 小的放前面,频次大的放后面。如果频次相等,就从当前节点往后遍历,直到找到第一个频次比它大的元素,并插入到它前面。(当然,如果遍历到了tail,则插入到tail前面)这样可以保证同频次的元素,最近访问的总是在最后边。
PS:哨兵节点只是为了占位,实际并不存储有效数据,只是为了链表插入和删除时,不用再判断当前节点的位置。不然的话,若当前节点占据了头结点或尾结点的位置,还需要重新赋值头尾节点元素,较麻烦。
为了便于理解新节点如何插入到链表中合适的位置,作图如下:
代码如下:
public class LFUCache {
public static void main(String[] args) {
LFUCache cache = new LFUCache(2);
cache.put(1, 1);
cache.put(2, 2);
// 返回 1
System.out.println(cache.get(1));
cache.put(3, 3); // 去除 key 2
// 返回 -1 (未找到key 2)
System.out.println(cache.get(2));
// 返回 3
System.out.println(cache.get(3));
cache.put(4, 4); // 去除 key 1
// 返回 -1 (未找到 key 1)
System.out.println(cache.get(1));
// 返回 3
System.out.println(cache.get(3));
// 返回 4
System.out.println(cache.get(4));
}
private Map<Integer,Node> cache;
private Node head;
private Node tail;
private int capacity;
private int size;
public LFUCache(int capacity) {
this.capacity = capacity;
this.cache = new HashMap<>();
/**
* 初始化头结点和尾结点,并作为哨兵节点
*/
head = new Node();
tail = new Node();
head.next = tail;
tail.pre = head;
}
public int get(int key) {
Node node = cache.get(key);
if(node == null) return -1;
node.freq++;
moveToPostion(node);
return node.value;
}
public void put(int key, int value) {
if(capacity == 0) return;
Node node = cache.get(key);
if(node != null){
node.value = value;
node.freq++;
moveToPostion(node);
}else{
//如果元素满了
if(size == capacity){
//直接移除最前面的元素,因为这个节点就是频次最小,且最久未访问的节点
cache.remove(head.next.key);
removeNode(head.next);
size--;
}
Node newNode = new Node(key, value);
//把新元素添加进来
addNode(newNode);
cache.put(key,newNode);
size++;
}
}
//只要当前 node 的频次大于等于它后边的节点,就一直向后找,
// 直到找到第一个比当前node频次大的节点,或者tail节点,然后插入到它前面
private void moveToPostion(Node node){
Node nextNode = node.next;
//先把当前元素删除
removeNode(node);
//遍历到符合要求的节点
while (node.freq >= nextNode.freq && nextNode != tail){
nextNode = nextNode.next;
}
//把当前元素插入到nextNode前面
node.pre = nextNode.pre;
node.next = nextNode;
nextNode.pre.next = node;
nextNode.pre = node;
}
//添加元素(头插法),并移动到合适的位置
private void addNode(Node node){
node.pre = head;
node.next = head.next;
head.next.pre = node;
head.next = node;
moveToPostion(node);
}
//移除元素
private void removeNode(Node node){
node.pre.next = node.next;
node.next.pre = node.pre;
}
class Node {
int key;
int value;
int freq = 1;
//当前节点的前一个节点
Node pre;
//当前节点的后一个节点
Node next;
public Node(){
}
public Node(int key ,int value){
this.key = key;
this.value = value;
}
}
}
可以看到不管是插入元素还是删除元素时,都不需要额外的判断,这就是设置哨兵节点的好处。
由于每次访问元素的时候,都需要按一定的规则把元素放置到合适的位置,因此,元素需要从前往后一直遍历。所以,时间复杂度 O(n)。