首页  >  文章  >  web前端  >  Leetcode #Memoize

Leetcode #Memoize

Patricia Arquette
Patricia Arquette原创
2024-10-02 06:43:30601浏览

给定一个函数 fn,返回该函数的记忆版本。

memoized 函数是永远不会使用相同输入调用两次的函数。相反,它将返回一个缓存值。

您可以假设有 3 种可能的输入函数:sum、fib 和阶乘。

sum 接受两个整数 a 和 b 并返回 a b。假设如果已经为参数 (b, a) 缓存了一个值,其中 a != b,则该值不能用于参数 (a, b)。例如,如果参数是 (3, 2) 和 (2, 3),则应进行两次单独的调用。
fib 接受单个整数 n,如果 n 阶乘接受单个整数 n,如果 n

示例1:

输入:

fnName = "sum"
actions = ["call","call","getCallCount","call","getCallCount"]
values = [[2,2],[2,2],[],[1,2],[]]

输出: [4,4,1,3,2]
说明:

const sum = (a, b) => a + b;
const memoizedSum = memoize(sum);
memoizedSum(2, 2); // "call" - returns 4. sum() was called as (2, 2) was not seen before.
memoizedSum(2, 2); // "call" - returns 4. However sum() was not called because the same inputs were seen before.
// "getCallCount" - total call count: 1
memoizedSum(1, 2); // "call" - returns 3. sum() was called as (1, 2) was not seen before.
// "getCallCount" - total call count: 2

示例2:

输入:

fnName = "factorial"
actions = ["call","call","call","getCallCount","call","getCallCount"]
values = [[2],[3],[2],[],[3],[]]

输出: [2,6,2,2,6,2]
说明:

const factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1));
const memoFactorial = memoize(factorial);
memoFactorial(2); // "call" - returns 2.
memoFactorial(3); // "call" - returns 6.
memoFactorial(2); // "call" - returns 2. However factorial was not called because 2 was seen before.
// "getCallCount" - total call count: 2
memoFactorial(3); // "call" - returns 6. However factorial was not called because 3 was seen before.
// "getCallCount" - total call count: 2

示例 3:

输入:

fnName = "fib"
actions = ["call","getCallCount"]
values = [[5],[]]

输出: [8,1]
说明:

fib(5) = 8 // "call"
// "getCallCount" - total call count: 1

约束:

> 0 <= a, b <= 105
> 1 <= n <= 10
> 0 <= actions.length <= 105
> actions.length === values.length

actions[i] 是“call”和“getCallCount”之一
fnName 是“sum”、“factorial”和“fib”之一

解决方案

Leetcode #Memoize

当您继续开发和优化 JavaScript 应用程序时,请记住记忆的力量。通过确定正确的函数来记忆并实施适当的缓存策略,您可以显着提高性能,并为您的客户创造更加无缝和响应更快的用户体验。

希望这篇文章对您有所帮助。如果您喜欢这篇文章,请点赞,并随时在评论部分留下任何疑问。这就是今天的全部内容。

以上是Leetcode #Memoize的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn