首页 > web前端 > js教程 > 正文

Leetcode #Memoize

Patricia Arquette
发布: 2024-10-02 06:43:30
原创
585 人浏览过

给定一个函数 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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!