-
- Notifications
You must be signed in to change notification settings - Fork 5.8k
Closed
Description
Map stores order of insertion and internally use a doubly-linked list to achieve this.
sample code to demonstrate: get and put time complexity: O(1)
/** * @param {number} capacity */ var LRUCache = function(capacity) { this.capacity = capacity; this.cache = new Map(); }; /** * @param {number} key * @return {number} */ LRUCache.prototype.get = function(key) { if(this.cache.has(key)){ let value = this.cache.get(key); this.cache.delete(key); this.cache.set(key,value); return value; } else{ return -1; } }; /** * @param {number} key * @param {number} value * @return {void} */ LRUCache.prototype.put = function(key, val) { if(this.cache.has(key)){ //refresh the cache this.cache.delete(key); this.cache.set(key,val); } else{ if(this.cache.size===this.capacity){ this.cache.delete(this.cache.keys().next().value); } this.cache.set(key,val); } }; Metadata
Metadata
Assignees
Labels
No labels