一、手写算法
https://leetcode-cn.com/problems/lru-cache/
思路
代码
```javascript /**- @param {number} capacity */ var LRUCache = function(capacity) { this.data = new Map(); this.max = capacity; };
/**
- @param {number} key
- @return {number} */ LRUCache.prototype.get = function(key) { if(this.data.has(key)){ let value = this.data.get(key); this.data.delete(key) this.put(key,value) return value }else{ return -1 }
};
/**
- @param {number} key
- @param {number} value
- @return {void} / LRUCache.prototype.put = function(key, value) { if(this.data.has(key)){ this.data.delete(key); } this.data.set(key,value); if(this.data.size > this.max){ this.data.delete(this.data.keys().next().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)
*/
```
复杂度分析
- 时间复杂度:O(N)
- 空间复杂度:O(N)
二、编程题
//2.手写题:https://bigfrontend.dev/problem/implement-Promise-race
/**
* @param {Array<Promise>} promises
* @return {Promise}
*/
function race(promises) {
// your code here
if(promises.length === 0){
return Promise.resolve([]);
}
return new Promise((resolve,reject)=>{
let _promises = promises.map((promise)=>{
promise.then(resolve,reject)
})
})
}