题目描述:
运用你所掌握的数据结构,设计和实现一个 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); // 返回 1cache.put(3, 3); // 该操作会使得密钥 2 作废cache.get(2); // 返回 -1 (未找到)cache.put(4, 4); // 该操作会使得密钥 1 作废cache.get(1); // 返回 -1 (未找到)cache.get(3); // 返回 3cache.get(4); // 返回 4
算法实现:
/*** @param {number} capacity*/var LRUCache = function(capacity) {this.cache = new Map()this.capacity = capacity};/*** @param {number} key* @return {number}*/LRUCache.prototype.get = function(key) {var cache = this.cacheif (cache.has(key)) {var temp = cache.get(key)cache.delete(key)cache.set(key, temp)return temp} else {return -1}};/*** @param {number} key* @param {number} value* @return {void}*/LRUCache.prototype.put = function(key, value) {var cache = this.cacheif (cache.has(key)) {cache.delete(key)} else if (cache.size >= this.capacity) {cache.delete(cache.keys().next().value)}cache.set(key, value)};/*** 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)*/
思考:
运用了es6的Map方法,很精妙,Map本身是键值对的集合,又可以用方法来添加和删除键值对,对于这道题很契合。
总结:
好久没有看es6了,发现有好多不常用的东西又忘的差不多了,做了这道题又重新看了一下阮一峰的set与map数据结构,受益颇深,这段时间打算再看一遍es6,温故而知新。
