Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
题意:实现LRU算法,最近最少使用替换,也就是,当cache里存满时,有新的内容到来,首先淘汰最久没有使用的内容,注意,当有put或get操作执行相应内容,都算使用,例如当页面顺序为:2,3,4,缓存大小为3时
这时有一个put(3,1),那么页面顺序变为 3,2,4
之后get(4) 页面顺序变为4,3,2
当有新内容到来时,put(5,2) 页面变为 5,4,3
代码:主要利用两个linkedList,一个记录key,一个记录value,依据上述机制进行操作。
在写代码过程中,遇到了一些问题https://blog.youkuaiyun.com/Lin_QC/article/details/89326567
class LRUCache {
public LinkedList L1=new LinkedList();
public LinkedList L2=new LinkedList();
public int ca;
public int v=0;
public LRUCache(int capacity) {
this.ca=capacity;
}
public int get(int key) {
if(!this.L1.contains(key)) return -1;
else {
int index=this.L1.indexOf(key);
this.L1.addFirst(key);
this.L2.addFirst(this.L2.get(index));
int re=Integer.parseInt(this.L2.get(0).toString());
this.L1.remove(index+1);
this.L2.remove(index+1);
return re;
}
}
public void put(int key, int value) {
if(this.L1.contains(key)){
int index=this.L1.indexOf(key);
this.L1.remove(index);
this.L2.remove(index);
this.L1.addFirst(key);
this.L2.addFirst(value);
}
else{
this.L1.addFirst(key);
this.L2.addFirst(value);
if(this.v<this.ca){
this.v++;
}
else{
this.L1.removeLast();
this.L2.removeLast();
}
}
}
}
/**
* 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);
*/
LRU缓存机制实现
本文详细介绍了如何设计和实现一个基于链表的LRU(最近最少使用)缓存算法,该算法能在O(1)的时间复杂度下完成get和put操作。通过两个链表分别记录key和value,遵循LRU机制进行操作,解决缓存容量限制下的数据更新问题。
942

被折叠的 条评论
为什么被折叠?



