什么是LRU
百度和谷歌有相关的连接介绍,本文不赘述。
LRU_百度百科
题目
链接:LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(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.
思路
用一个Entry类保存键和值,用一个List作为主要容器。在进行get和set的操作时,如果是访问List中已有的Entry元素,则将其移动至List的最前端;如果set操作时是插入一个新的Entry元素,则将其插入List的最前端。在进行set操作时,如果List的大小达到容量capacity,则将List尾部的元素移除之后再进行插入操作。
代码
public class LRUCache {
private int capacity;
private List<Entry> list;
/*
* @param capacity: An integer
*/public LRUCache(int capacity) {
this.capacity = capacity;
list = new ArrayList<>(capacity);
}
/*
* @param key: An integer
* @return: An integer
*/
public int get(int key) {
Entry visitEntry = null;
for(Entry e : list){
if(e.key == key){
visitEntry = e;
break;
}
}
if(visitEntry != null){
list.remove(visitEntry);
list.add(0, visitEntry);
return visitEntry.value;
}
return -1;
}
/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
public void set(int key, int value) {
Entry visitEntry = null;
for(Entry e : list){
if(e.key == key){
visitEntry = e;
}
}
if (visitEntry!=null){
visitEntry.value = value;
list.remove(visitEntry);
list.add(0, visitEntry);
}else{
Entry e = new Entry(key,value);
if(list.size()>=capacity){
list.remove(list.size()-1);
}
list.add(0, e);
}
}
private class Entry{
private int key;
private int value;
public Entry (int key, int value){
this.key = key;
this.value = value;
}
public void set(int key, int value){
this.key = key;
this.value = value;
}
public int getKey(){
return key;
}
public int getValue(){
return value;
}
}
}