[LeetCode][JavaScript]LRU Cache

LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

https://leetcode.com/problems/lru-cache/

 

 


 

 

最近最少使用。

开一个容量为capacity的容器,如果最近访问过(get和set都算访问),就把这个元素放到第一个,超出capacity就删掉最后一个元素。

我这边用了js的数组,可以AC,但比较慢,用链表可以快一些,主要是移除数组里指定元素的操作费时:

 this.queue = this.queue.slice(0,i).concat(this.queue.slice(i + 1));

另开一个set对象记录在队列中的元素,以空间换时间,这样查找元素的效率就是O(logn)

 1 /**
 2  * @constructor
 3  */
 4 var LRUCache = function(capacity) {
 5     this.capacity = capacity;
 6     this.keyMap = new Set();
 7     this.queue = []; 
 8 };
 9 
10 /**
11  * @param {number} key
12  * @returns {number}
13  */
14 LRUCache.prototype.get = function(key) {
15     if(this.keyMap.has(key)){
16         for(var i = 0; i < this.queue.length; i++){
17             if(this.queue[i].key === key){
18                 var value = this.queue[i].value;
19                 this.queue = this.queue.slice(0,i).concat(this.queue.slice(i + 1));
20                 this.queue.unshift({key : key, value : value}); 
21                 return value;
22             }
23         }
24     }
25     return -1;
26 };
27 
28 /**
29  * @param {number} key
30  * @param {number} value
31  * @returns {void}
32  */
33 LRUCache.prototype.set = function(key, value) {
34     if(this.keyMap.has(key)){
35         var index = -1;
36         for(var i = 0; i < this.queue.length; i++){
37             if(this.queue[i].key === key){
38                 index = i;
39                 break;
40             }
41         }
42         this.queue = this.queue.slice(0,index).concat(this.queue.slice(index + 1));
43     }else{
44         this.keyMap.add(key);
45     }
46     this.queue.unshift({key : key, value : value}); 
47 
48     if(this.queue.length > this.capacity){
49         var pop = this.queue.pop();
50         this.keyMap.delete(pop.key);
51     }
52 };

 

 

 

 

posted @ 2015-06-14 21:36  `Liok  阅读(1031)  评论(0编辑  收藏  举报