LintCode算法题:LRU Cache

什么是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;
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值