Skip to content

Commit 068ef10

Browse files
committed
feat: add solutions to lc problem: No.2623
No.2623.Memoize
1 parent 132fc86 commit 068ef10

File tree

3 files changed

+81
-2
lines changed

3 files changed

+81
-2
lines changed

solution/2600-2699/2623.Memoize/README.md

+31-1
Original file line numberDiff line numberDiff line change
@@ -93,14 +93,44 @@ memoFactorial(3); // 返回 6。 没有调用 factorial(),因为前面有相
9393

9494
<!-- 这里可写通用的实现逻辑 -->
9595

96+
**方法一:哈希表**
97+
98+
我们可以使用哈希表来存储函数的参数和返回值,当再次调用函数时,如果参数已经存在于哈希表中,则直接返回哈希表中的值,否则调用函数并将返回值存入哈希表中。
99+
100+
时间复杂度 $O(1)$,空间复杂度 $O(n)$。其中 $n$ 为函数的参数个数。
101+
96102
<!-- tabs:start -->
97103

98104
### **TypeScript**
99105

100106
<!-- 这里可写当前语言的特殊实现逻辑 -->
101107

102108
```ts
103-
109+
type Fn = (...params: any) => any;
110+
111+
function memoize(fn: Fn): Fn {
112+
const cache: Record<any, any> = {};
113+
114+
return function (...args) {
115+
if (args in cache) {
116+
return cache[args];
117+
}
118+
const result = fn(...args);
119+
cache[args] = result;
120+
return result;
121+
};
122+
}
123+
124+
/**
125+
* let callCount = 0;
126+
* const memoizedFn = memoize(function (a, b) {
127+
* callCount += 1;
128+
* return a + b;
129+
* })
130+
* memoizedFn(2, 3) // 5
131+
* memoizedFn(2, 3) // 5
132+
* console.log(callCount) // 1
133+
*/
104134
```
105135

106136
### **...**

solution/2600-2699/2623.Memoize/README_EN.md

+25-1
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,31 @@ memoFactorial(3); // Returns 6. However factorial was not called because 3 was s
9292
### **TypeScript**
9393

9494
```ts
95-
95+
type Fn = (...params: any) => any;
96+
97+
function memoize(fn: Fn): Fn {
98+
const cache: Record<any, any> = {};
99+
100+
return function (...args) {
101+
if (args in cache) {
102+
return cache[args];
103+
}
104+
const result = fn(...args);
105+
cache[args] = result;
106+
return result;
107+
};
108+
}
109+
110+
/**
111+
* let callCount = 0;
112+
* const memoizedFn = memoize(function (a, b) {
113+
* callCount += 1;
114+
* return a + b;
115+
* })
116+
* memoizedFn(2, 3) // 5
117+
* memoizedFn(2, 3) // 5
118+
* console.log(callCount) // 1
119+
*/
96120
```
97121

98122
### **...**
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
type Fn = (...params: any) => any;
2+
3+
function memoize(fn: Fn): Fn {
4+
const cache: Record<any, any> = {};
5+
6+
return function (...args) {
7+
if (args in cache) {
8+
return cache[args];
9+
}
10+
const result = fn(...args);
11+
cache[args] = result;
12+
return result;
13+
};
14+
}
15+
16+
/**
17+
* let callCount = 0;
18+
* const memoizedFn = memoize(function (a, b) {
19+
* callCount += 1;
20+
* return a + b;
21+
* })
22+
* memoizedFn(2, 3) // 5
23+
* memoizedFn(2, 3) // 5
24+
* console.log(callCount) // 1
25+
*/

0 commit comments

Comments
 (0)