File tree 3 files changed +81
-2
lines changed
solution/2600-2699/2623.Memoize
3 files changed +81
-2
lines changed Original file line number Diff line number Diff line change @@ -93,14 +93,44 @@ memoFactorial(3); // 返回 6。 没有调用 factorial(),因为前面有相
93
93
94
94
<!-- 这里可写通用的实现逻辑 -->
95
95
96
+ ** 方法一:哈希表**
97
+
98
+ 我们可以使用哈希表来存储函数的参数和返回值,当再次调用函数时,如果参数已经存在于哈希表中,则直接返回哈希表中的值,否则调用函数并将返回值存入哈希表中。
99
+
100
+ 时间复杂度 $O(1)$,空间复杂度 $O(n)$。其中 $n$ 为函数的参数个数。
101
+
96
102
<!-- tabs:start -->
97
103
98
104
### ** TypeScript**
99
105
100
106
<!-- 这里可写当前语言的特殊实现逻辑 -->
101
107
102
108
``` 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
+ */
104
134
```
105
135
106
136
### ** ...**
Original file line number Diff line number Diff line change @@ -92,7 +92,31 @@ memoFactorial(3); // Returns 6. However factorial was not called because 3 was s
92
92
### ** TypeScript**
93
93
94
94
``` 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
+ */
96
120
```
97
121
98
122
### ** ...**
Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments