首页 > 系统服务 > 详细

leetcode: LRU Cache

时间:2016-07-11 02:04:14      阅读:281      评论:0      收藏:0      [点我收藏+]

问题描述:

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.

原问题链接:https://leetcode.com/problems/lru-cache/

?

问题分析

  这个问题的思路是希望能够设计一个类似于cache的数据结构,这个结构能够按照给定的大小构造。同时在进行get操作的时候能够查找到匹配的值,如果没有就返回-1。 set操作的时候则将将给定的值加入到里面,但是如果元素数量超过容量时,需要删除目前最不常用的元素。

  如果从头开始设计这个结构的话会比较复杂,当然,这里有一个偷懒取巧的办法,就是利用java类库里现成的LinkedHashMap。它本身就已经支持这种访问了。

  这是一种详细的实现代码:

?

import java.util.LinkedHashMap;

public class LRUCache {
    private LinkedHashMap<Integer, Integer> map;
    private final int CAPACITY;
    public LRUCache(int capacity) {
        CAPACITY = capacity;
        map = new LinkedHashMap<Integer, Integer>(capacity, 1.0f, true){
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() > CAPACITY;
            }
        };
    }
    public int get(int key) {
        return map.getOrDefault(key, -1);
    }
    public void set(int key, int value) {
        map.put(key, value);
    }
}

leetcode: LRU Cache

原文:http://shmilyaw-hotmail-com.iteye.com/blog/2309946

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!