-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.lru-缓存.ts
50 lines (46 loc) · 1.08 KB
/
146.lru-缓存.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @lc app=leetcode.cn id=146 lang=typescript
*
* [146] LRU 缓存
*/
// @lc code=start
class LRUCache {
private capacity: number;
private cache: Map<number, number>;
constructor(capacity: number) {
this.capacity = capacity;
this.cache = new Map<number, number>();
}
get(key: number): number {
if (this.cache.has(key)) {
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value!);
return value!;
} else {
return -1;
}
}
put(key: number, value: number): void {
if (this.cache.has(key)) {
this.cache.delete(key);
this.cache.set(key, value);
} else {
if (this.cache.size >= this.capacity) {
// 用这种方法去删除第一个
for (const [key, value] of this.cache) {
this.cache.delete(key);
break;
}
}
this.cache.set(key, 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)
*/
// @lc code=end