add: LRU缓存机制
This commit is contained in:
parent
06d357b002
commit
3770b30040
@ -343,6 +343,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
|||||||
- LeetCode 860. 柠檬水找零 <https://leetcode-cn.com/problems/lemonade-change/>
|
- LeetCode 860. 柠檬水找零 <https://leetcode-cn.com/problems/lemonade-change/>
|
||||||
- LintCode 1509. 柠檬水找零 <https://www.lintcode.com/problem/lemonade-change/description>
|
- LintCode 1509. 柠檬水找零 <https://www.lintcode.com/problem/lemonade-change/description>
|
||||||
|
|
||||||
|
- [LRU缓存机制](src/array/lru-cache.js)
|
||||||
|
|
||||||
|
- LeetCode 146. LRU缓存机制 <https://leetcode-cn.com/problems/lru-cache/>
|
||||||
|
- LintCode 134. LRU缓存策略 <https://www.lintcode.com/problem/lru-cache/description>
|
||||||
|
|
||||||
## 栈
|
## 栈
|
||||||
|
|
||||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||||
|
21
src/array/lru-cache.js
Normal file
21
src/array/lru-cache.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
export default class LRUCache {
|
||||||
|
constructor (capacity) {
|
||||||
|
this.max = capacity; this.map = new Map()
|
||||||
|
}
|
||||||
|
|
||||||
|
get (key) {
|
||||||
|
const value = this.map.get(key)
|
||||||
|
if (value !== undefined) {
|
||||||
|
this.map.delete(key)
|
||||||
|
this.map.set(key, value)
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
put (key, value) {
|
||||||
|
this.map.delete(key)
|
||||||
|
this.map.set(key, value)
|
||||||
|
if (this.map.size > this.max) this.map.delete(this.map.keys().next().value)
|
||||||
|
}
|
||||||
|
}
|
15
test/array/lru-cache.test.js
Normal file
15
test/array/lru-cache.test.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import LRUCache from '../../src/array/lru-cache'
|
||||||
|
|
||||||
|
test('LRU缓存机制', () => {
|
||||||
|
const cache = new LRUCache(2 /* 缓存容量 */)
|
||||||
|
|
||||||
|
cache.put(1, 1)
|
||||||
|
cache.put(2, 2)
|
||||||
|
expect(cache.get(1)).toBe(1) // 返回 1
|
||||||
|
cache.put(3, 3) // 该操作会使得密钥 2 作废
|
||||||
|
expect(cache.get(2)).toBe(-1) // 返回 -1 (未找到)
|
||||||
|
cache.put(4, 4) // 该操作会使得密钥 1 作废
|
||||||
|
expect(cache.get(1)).toBe(-1) // 返回 -1 (未找到)
|
||||||
|
expect(cache.get(3)).toBe(3) // 返回 3
|
||||||
|
expect(cache.get(4)).toBe(4) // 返回 4
|
||||||
|
})
|
Loading…
Reference in New Issue
Block a user