LRU Cache leetcode
来源:互联网 发布:while的用法c语言 编辑:程序博客网 时间:2024/06/05 05:54
1.自己想的
public class LRUCache {
public LinkedList<Integer> used=new LinkedList<Integer>();
public Map<Integer, Integer> map=new HashMap<Integer,Integer>();
public int len;
public int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
len = 0;
}
public int get(int key) {
if(map.containsKey(key)){
//System.out.println(used.toString());
used.remove((Object)key);
used.addFirst(key);
return map.get(key);
}
else{
System.out.println("没得到的元素:"+key);
return -1;
}
}
public void put(int key, int value) {
if(map.containsKey(key)){
map.put(key, value);
used.remove((Object)key);
used.addFirst(key);
}
else{
if(len<capacity){
used.addFirst(key);
map.put(key, value);
len++;
}
else{
int removedKey=used.getLast();
used.removeLast();
System.out.println("map移除结点:"+removedKey);
map.remove(removedKey);
map.put(key, value);
used.addFirst(key);
}
}
}
}
2.基于LinkedHashMap
public class LRUCache extends LinkedHashMap<Integer,Integer>{
private int maxcapacity;
public LRUCache(int capacity) {
super(capacity,0.75f,true);
this.maxcapacity=capacity;
}
public int get(int key) {
Integer vaule=super.get(key);
if(vaule==null)return -1;
else return vaule;
}
public void set(int key, int value) {
super.put(key,value);
}
protected boolean removeEldestEntry(Map.Entry<Integer,Integer> eldest)
{
return size()>maxcapacity;
}
}
- LeetCode LRU 缓存 LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- leetcode之LRU Cache
- [LeetCode]LRU Cache
- [LeetCode] LRU Cache
- leetcode LRU Cache
- LeetCode题解:LRU Cache
- LeetCode | LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- LeetCode OJ:LRU Cache
- Leetcode LRU Cache
- LeetCode - LRU Cache
- [Leetcode] LRU Cache (Java)
- Elasticsaech-head插件安装 Elasticsearch5.X
- 树的高度
- ntp时间服务同步
- 解决Ajax 跨域问题
- HDU 5882 Balanced Game 分析+欧拉图
- LRU Cache leetcode
- Android生命周期详解
- 数据库的事务的特性 ---- 学习笔记
- 阻止事件冒泡和组阻止默认事件和return false的区别
- Android模拟器使用桥接方式连接网络
- 使用sklearn做单机特征工程
- python3 -- subprocess,excel读写库实践整理
- hdu 4474 dfs+减枝
- struts2--动态方法调用的三种方式