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

Leetcode #Memoize

Patricia Arquette
Patricia Arquette原創
2024-10-02 06:43:30602瀏覽

給定一個函數 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