题解 | #设计LRU缓存结构#

设计LRU缓存结构

http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61

使用python进行解答,使到dist和[]的一些内置方法。

  • cache_list:作为缓存
  • tmp:记录最近使用的顺序
  • result:记录操作结果(get操作)

代码:

#
# lru design
# @param operators int整型二维数组 the ops
# @param k int整型 the k
# @return int整型一维数组
#
class Solution:
    def LRU(self , operators , k ):
        cache_list = {}
        tmp = []
        result = []
        for operator in operators:
            print("==============================================================")
            # set操作
            if operator[0] == 1:
                print("当前操作是set:{}".format(operator))
                # 如果缓存已经满了,则更新
                if len(tmp) == k:
                    a=tmp.pop(0)
                    cache_list.pop(a)
                tmp.append(str(operator[1]))
                cache_list[str(operator[1])]=operator[2]
            else:
                print("当前操作是get:{}".format(operator))
#                 if cache_list.has_key(str(operator[1])):
                if str(operator[1]) in cache_list:
                    tmp.remove(str(operator[1]))
                    tmp.append(str(operator[1]))
                    result.append(cache_list[str(operator[1])])
                else:
                    result.append(-1)
            print("当前操作后的缓存为:{}".format(cache_list))
            print("缓存顺序为:{}".format(tmp))
            print("当前结果为:{}".format(result))
        return result

测试:

solution = Solution()
result= solution.LRU([[1,1,1],[1,2,2],[1,3,2],[2,1],[1,4,4],[2,2]],3)
print(result)

输出:

==============================================================
当前操作是set:[1, 1, 1]
当前操作后的缓存为:{'1': 1}
缓存顺序为:['1']
当前结果为:[]
==============================================================
当前操作是set:[1, 2, 2]
当前操作后的缓存为:{'1': 1, '2': 2}
缓存顺序为:['1', '2']
当前结果为:[]
==============================================================
当前操作是set:[1, 3, 2]
当前操作后的缓存为:{'1': 1, '2': 2, '3': 2}
缓存顺序为:['1', '2', '3']
当前结果为:[]
==============================================================
当前操作是get:[2, 1]
当前操作后的缓存为:{'1': 1, '2': 2, '3': 2}
缓存顺序为:['2', '3', '1']
当前结果为:[1]
==============================================================
当前操作是set:[1, 4, 4]
当前操作后的缓存为:{'1': 1, '3': 2, '4': 4}
缓存顺序为:['3', '1', '4']
当前结果为:[1]
==============================================================
当前操作是get:[2, 2]
当前操作后的缓存为:{'1': 1, '3': 2, '4': 4}
缓存顺序为:['3', '1', '4']
当前结果为:[1, -1]
[1, -1]
全部评论

相关推荐

迷茫的大四🐶:摊牌了,我是25届的,你们也不招我
点赞 评论 收藏
分享
10-29 22:30
吉林大学 Java
同专业学长学姐,去互联网大厂的起薪 15k+,去国企 IT 岗的也有 12k+,就连去中小厂的都基本 13k 起步😤 我投的传统行业技术岗,拼死拼活拿到 1Woffer,本来还挺开心,结果逛了圈牛客直接破防,同是校招生,行业差距怎么就这么大啊!
喵喵喵6_6:应该哪里不对吧,大厂都是20k以上的,10k那种对于985本的学生基本就是点击一下过了笔试就送的,我前两天刚拿了一个11k,笔试完第2天就打电话了,非科班。坏消息是c++岗开这么低真是刷新认知了
校招生月薪1W算什么水平
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务