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.

思路:Java的LinkedHashMap可以实现最近最少使用(LRU)的次序。类似于HashMap。详见《JAVA编程思想(第4版)》P487.

题目要求是一个固定大小的cache,因此需要一个变量maxCapacity来记录容量大小,用LinkedHashMap存储数据。在添加数据set()方法时,判断一下是否达到maxCapacity,如果cache已经满了,remove掉最长时间不使用的数据,然后put进新的数据。

注意:HashMap,LinkedHashMap,TreeMap的区别,详细看看StackOverFlow

LinkedHashMap最常用的是LRU cache的实现。
如果用C++实现的话, hashmap + 双向链表:用 双向链表记录value 用hashmap记录 key值在链表中的位置(指针)。

unordered_map<int, list<CacheNode>:: iterator> cacheMap;

题解:

import java.util.LinkedHashMap;

public class LRUCache {

	LinkedHashMap<Integer, Integer> linkedmap;
int maxCapacity; public LRUCache(int capacity) {
this.maxCapacity = capacity;
this.linkedmap = new LinkedHashMap<Integer, Integer>(capacity, 1f, true);
} public int get(int key) {
if (linkedmap.containsKey(key))
return linkedmap.get(key);
else
return -1;
} public void set(int key, int value) {
int size = linkedmap.size();
if ((size < maxCapacity) || (linkedmap.containsKey(key))) {
linkedmap.put(key, value);
} else if (size >= maxCapacity) {
Iterator<Integer> it = linkedmap.keySet().iterator();//iterator method is superior the toArray(T[] a) method.
linkedmap.remove(it.next());
linkedmap.put(key, value);
}
}
}

结题遇到的问题:

1.下面这段代码提交的时候超时了。

import java.util.LinkedHashMap;

public class LRUCache {
LinkedHashMap<Integer, Integer> linkedmap;
int maxCapacity; public LRUCache(int capacity) {
this.maxCapacity = capacity;
this.linkedmap = new LinkedHashMap<Integer, Integer>(capacity, 1f, true);
} public int get(int key) {
if (linkedmap.containsKey(key))
return linkedmap.get(key);
else
return -1;
} public void set(int key, int value) {
int size = linkedmap.size();
if ((size < maxCapacity) || (linkedmap.containsKey(key))) {
linkedmap.put(key, value);
} else if (size >= maxCapacity) {
Integer[] keyArray = linkedmap.keySet().toArray(new Integer[0]);//这是超时的代码,采用Iterator不会超时。
linkedmap.remove(keyArray[0]);
linkedmap.put(key, value);
}
} }

2.Roger自己实现LinkedHashMap的功能,采用双向链表和哈希表。效率略低于LinkedHashMap.(644ms>548ms)  

import java.util.HashMap;

public class LRUCache {

	private HashMap<Integer, Entry<Integer>> index;
private UDFList<Integer> data; public LRUCache(int capacity) {
index = new HashMap<Integer, Entry<Integer>>(capacity);
data = new UDFList<Integer>(capacity);
} public int get(int key) {
if (!isExist(key)) {
index.remove(key);
return -1;
}
if (!index.get(key).equals(data.head)) {
Entry<Integer> nodePtr = data.adjust(index.get(key));
index.put(key, nodePtr);
}
return index.get(key).element;
} public void set(int key, int value) {
if (isExist(key)) {
data.remove(index.get(key));
}
index.put(key, data.push(value));
} private boolean isExist(int key) {
if (index.get(key) == null) {
return false;
}
if (index.get(key).element == null) {
return false;
}
return true;
} public class UDFList<E> {
public Entry<E> head;
public Entry<E> tail;
public final int size;
public int length = 0; public UDFList(int size) {
head = new Entry<E>(null, null, null);
tail = head;
this.size = size;
} public Entry<E> adjust(Entry<E> node) {
if (node.equals(tail)) {
tail = tail.previous;
tail.next = null;
node.previous = null;
} else if (node.equals(head)) {
node = null;
return head;
} else {
node.previous.next = node.next;
node.next.previous = node.previous;
}
head.previous = node;
node.next = head;
head = node;
node = null;
return head;
} public Entry<E> push(E e) {
Entry<E> newNode = new Entry<E>(e, null, null);
if (length == 0) {
head = newNode;
tail = head;
} else {
head.previous = newNode;
newNode.next = head;
head = newNode;
}
if (length == size) {
remove(tail);
}
length++;
return head;
} public void remove(Entry<E> node) {
if (node == null)
return;
node.element = null;
if (node.equals(head)) {
head = head.next;
} else if (node.equals(tail)) {
tail = tail.previous;
tail.next = null;
} else {
node.previous.next = node.next;
node.next.previous = node.previous;
}
node = null;
length--;
}
} public class Entry<E> {
public E element;
public Entry<E> previous;
public Entry<E> next; public Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
}

  

  

LeetCode解题报告:LRU Cache的更多相关文章

  1. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  2. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  3. LeetCode题解: LRU Cache 缓存设计

    LeetCode题解: LRU Cache 缓存设计 2014年12月10日 08:54:16 邴越 阅读数 1101更多 分类专栏: LeetCode   版权声明:本文为博主原创文章,遵循CC 4 ...

  4. 【LeetCode】146. LRU Cache 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典+双向链表 日期 题目地址:https://le ...

  5. LRU算法&amp;&amp;LeetCode解题报告

    题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...

  6. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  7. 【LeetCode OJ】LRU Cache

    Problem Link: http://oj.leetcode.com/problems/lru-cache/ Long long ago, I had a post for implementin ...

  8. 【LeetCode】146. LRU Cache

    LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should suppo ...

  9. LeetCode OJ:LRU Cache(最近使用缓存)

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

随机推荐

  1. 使用内省方式操作JavaBean

    内省,英文中称作introspector.主要对javaBean进行操作,JavaBean是一个特殊的Java类,该类中方法名符合特定的规则(其实就是getXXX,setXXX),我们一般是利用get ...

  2. 使用SBT构建Scala项目

    既然决定要在Scala上下功夫,那就要下的彻底.我们入乡随俗,学一下SBT.sbt使用ivy作为库管理工具.ivy默认把library repository建在user home下面. 安装SBT 在 ...

  3. JDK1.8聚合操作

    在java8 JDK包含许多聚合操作(如平均值,总和,最小,最大,和计数),返回一个计算流stream的聚合结果.这些聚合操作被称为聚合操作.JDK除返回单个值的聚合操作外,还有很多聚合操作返回一个c ...

  4. sql - 选出指定范围的行

    Select no=Identity(int,1,1),* Into #temptable From dbo.tName order by fName --利用Identity函数生成记录序号 Sel ...

  5. 【转】怎样创建一个Xcode插件(Part 1)

      原文:How To Create an Xcode Plugin: Part 1/3 原作者:Derek Selander 译者:@yohunl 译者注:原文使用的是xcode6.3.2,我翻译的 ...

  6. mac下使用自带的apache与php

    启动apache 运行命令 sudo  apachectl -k start 启动apache 如果报 AH00526: Syntax error on line 20 of /private/etc ...

  7. iOS UITableviewWrapperView 和 automaticallyAdjustsScrollViewInsets属性

    关于在navigationController下面使用tableView在竖直方向会遇到frame的y值的困惑, 会遇到视图控制器的这个属性:automaticallyAdjustsScrollVie ...

  8. boost::xml————又一次失败的尝试

    尝试使用wptree来进行xml解析,又一次失败了,可以正常读取正常输出,但是使用wptree进行节点读取失败(乱码) 请看源码: DealXml.h #pragma once #include &l ...

  9. Net常用资源小集

    Visual Studio——IDEs工具之王,.NET开发者的必备IDE.Visual Studio提供非常强大的启动工具箱,并且还有一些让人惊喜的插件支持.在去年,微软发布了Visual Stud ...

  10. jQuery慢慢啃之ajax(九)

    1.jQuery.ajax(url,[settings])//通过 HTTP 请求加载远程数据 如果要处理$.ajax()得到的数据,则需要使用回调函数.beforeSend.error.dataFi ...