zoukankan      html  css  js  c++  java
  • leetcode刷题笔记一百四十六题 LRU缓存机制

    leetcode刷题笔记一百四十六题 LRU缓存机制

    源地址:146. LRU缓存机制

    问题描述:

    运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

    获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
    写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

    进阶:

    你是否可以在 O(1) 时间复杂度内完成这两种操作?

    示例:

    LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

    cache.put(1, 1);
    cache.put(2, 2);
    cache.get(1); // 返回 1
    cache.put(3, 3); // 该操作会使得关键字 2 作废
    cache.get(2); // 返回 -1 (未找到)
    cache.put(4, 4); // 该操作会使得关键字 1 作废
    cache.get(1); // 返回 -1 (未找到)
    cache.get(3); // 返回 3
    cache.get(4); // 返回 4

    //LRU缓存机制需要借助HashMap实现O(1)级别的操作,同时需要维护一个列表,用于记录使用顺序
    import scala.collection.mutable
    class LRUCache(_capacity: Int) {
        var hm = mutable.HashMap.empty[Int, Int]
        var lb = mutable.ListBuffer.empty[Int]
        //当前不重复数值容量,最大为capacity
        var size = 0
        //最大容量
        var capacity = _capacity
    
        def get(key: Int): Int = {
            //key值已经塞入
            if (hm.contains(key)){
                val li = lb.indexOf(key)
                //更新lb中key值位置到末尾,代表最近访问
                lb.remove(li)
                lb += key
                return hm(key)
            }
            //get不到,返回-1
            return -1
        }
    
        def put(key: Int, value: Int) {
            //已塞入key,只需更新key到末尾即可
            if (hm.contains(key)){
                hm(key) = value
                val li = lb.indexOf(key)
                lb.remove(li)
                lb += key
            }
            else{
                //如果此时已达容量上限,删去lb的头部元素
                if (size == capacity){
                    val lh = lb.head
                    hm -= lh
                    lb.remove(0)
                }
                //未达上限,更新size
                else size += 1
                //将新key添加
                hm(key) = value
                lb += key
            }
        }
    }
    
    /**
     * Your LRUCache object will be instantiated and called as such:
     * var obj = new LRUCache(capacity)
     * var param_1 = obj.get(key)
     * obj.put(key,value)
     */
    
  • 相关阅读:
    POJ_1066_Treasure Hunt_判断线段相交
    【转载】VS写汇编程序01:VS2015配置汇编语言开发环境
    【转载】汇编调试程序Debug使用
    【转载】C++ STL快速入门
    Longest Palindromic Substring
    Leetcode经典试题:Longest Substring Without Repeating Characters解析
    C++数组的初始化
    C++题目:回文数判断
    C++-int类型整数超出范围后的处理
    Memorise Me!——用数值做地址,实现快速查找
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13576112.html
Copyright © 2011-2022 走看看