Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day11

第一次接觸 Medium 等級的題目確實很難,思考方向是錯的,第一次一行都沒打出來就直接看答案(自己打的內容全錯而且沒一行是對的)

Day11: Memoize

問題描述:

Given a function fn, return a memoized version of that function.

memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.

You can assume there are 3 possible input functions: sum, fib, and factorial.

  • sum ****accepts two integers a and b and returns a + b.

  • fib ****accepts a single integer n and returns 1 if orotherwise.

    n <= 1

    fib(n - 1) + fib(n - 2)

  • factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise.

問題難度:Medium

問題限制:

  • 0 <= a, b <= 105
  • 1 <= n <= 10
  • 0 <= actions.length <= 105
  • actions.length === values.length
  • actions[i] is one of “call” and “getCallCount”
  • fnName is one of “sum”, “factorial” and “fib”

我的解題過程

題目的重點在於 memoized function ,它不會對相同的輸入被調用兩次。相反,它將返回緩存的值。

因此我們必須要先建立一個緩存的空間:

1
const cache = {}

使用者會自行設定他的function,因此我們要判斷他傳進來的function是否有被執行過,因此要先把傳進來的function變成字串:

1
const key = JSON.stringify(args);

並用if的判斷式來判斷跟cache裡的值是否一樣:

1
2
3
4
5
6
7
if (key in cache) {
return cache[key]
} else {
const result = fn(...args)
cache[key] = result
return result
}

以上內容皆是看完答案後再一次實作出來的

其他解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function memoize(fn) {

const cache = {};

return function(...args) {
const key = JSON.stringify(args);

if (key in cache) {
return cache[key];
}

const result = fn.apply(this, args);
cache[key] = result;

return result;
}

}

結論

看完解答後再實作確實就沒有感覺到這麼難,但在沒看解答前是真的想不出個所以然來。
只知道要去判斷之前時不是有執行過,但要怎麼去分辨使用者是輸入哪一個function那段就完全卡住了。
看了解說才知道有if (key in object) {}

key 是需要檢查的屬性名稱,object 是需要檢查的對象。

如果 object 對象中存在 key 屬性,則 key in object 語句返回 true,否則返回 false
這是之前沒有用過的語法,自己的JS真的還有得學。