You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
单次操作没有,但考虑实际应用场景,其实隐含着一个 while true 循环,循环体的操作是 get 或 put。不变式就是 ADT 的要求:「保持缓存按照使用顺序排序,且达到缓存上限时,新增之前要先剔除掉最末尾的缓存」。
functionDoubleLinkedNode(data){this.data=datathis.pre=nullthis.next=null}functionDoubleLinkedList(){this.head=newDoubleLinkedNode(null)this.tail=newDoubleLinkedNode(null)this.head.next=this.tailthis.tail.pre=this.headthis.size=0}DoubleLinkedList.prototype.add=function(node){// insert between this.head and this.head.nextnode.next=this.head.nextnode.pre=this.headthis.head.next.pre=nodethis.head.next=nodethis.size++}DoubleLinkedList.prototype.remove=function(node){// remove node from its pre and nextconst[pre,next]=[node.pre,node.next]pre.next=nextnext.pre=prenode.pre=node.next=nullthis.size--}DoubleLinkedList.prototype.pop=function(){// remove this.tail.preconstnode=this.tail.prethis.remove(node)returnnode}varLRUCache=function(capacity){this.capacity=capacitythis.size=0this._cache={}this._list=newDoubleLinkedList()}LRUCache.prototype.get=function(key){if(!(keyinthis._cache))return-1// if reuse some node// then must remove it from list// and readd itconstnode=this._cache[key]this._list.remove(node)this._list.add(node)// return value at lastreturnnode.data.value}LRUCache.prototype.put=function(key,value){// if key already existed// then remove the node from listif(keyinthis._cache)this._list.remove(this._cache[key])// if full// then must pop the tail.pre from list// and delete it from cacheelseif(this.size===this.capacity){constnode=this._list.pop()deletethis._cache[node.data.key]}// if not full, size++elsethis.size++// at last, add the new node into list and cacheconstnode=newDoubleLinkedNode({key, value})this._list.add(node)this._cache[key]=node}/** * 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) */
The text was updated successfully, but these errors were encountered:
题:运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥已经存在,则变更其数据值;如果密钥不存在,则插入该组「密钥/数据值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
要求 O(1) 时间复杂度内完成这两种操作。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lru-cache
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解:这是一道 ADT 设计题,通用解法是双向链表加哈希表实现有序哈希。面试时,最好手写实现,而不是直接使用自带的有序字典。
既然要求两种操作的复杂度均为
O(1)
,那还有「循环不变式」吗?单次操作没有,但考虑实际应用场景,其实隐含着一个 while true 循环,循环体的操作是 get 或 put。不变式就是 ADT 的要求:「保持缓存按照使用顺序排序,且达到缓存上限时,新增之前要先剔除掉最末尾的缓存」。
The text was updated successfully, but these errors were encountered: