Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day8

今天花了比平常還有久的一點時間,最後還是有稍微看一下答案

Day8: Function Composition

問題描述:

Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions.

The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))).

The function composition of an empty list of functions is the identity function f(x) = x.

You may assume each function in the array accepts one integer as input and returns one integer as output.

問題難度:Easy

問題限制:

  • 1000 <= x <= 1000
  • 0 <= functions.length <= 1000
  • all functions accept and return a single integer

我的解題思路

我連題目都看不懂了…

我的理解是給一個 array ,這個array裡面放的是function,然後要回傳出一個新的functionfn()

fn()會是長這樣: fn(x) = f(g(h(x))).

如果fn()裡面沒有任何值,那fn(x) = x

先從簡單的開始做起,如果 array 是空值:

1
2
3
4
5
if (functions.length === 0) {
return function(x) {
return x
}
}

接下來要處理 fn(x) = f(g(h(x))).

一開始就想說就是要讓他遍歷一次但是是要從後面回來,因此第一個版本的回答是這樣的:

1
2
3
4
5
return function(x) {
for (let i = functions.length; i >= 0; --i) {
functions[i](x)
}
}

但這樣回傳出來的是 functions[i] is not a function
想了一陣子才注意到我應該要設定變數來儲存x,因此改成:

1
2
3
4
5
6
7
8
return function(x) {
let newFn = x

for (let i = functions.length; i >= 0; --i) {
newFn = functions[i](newFn)
}
return newFn
}

但還使出現錯誤TypeError:functions[i] is not a function

這時我真的沒有想法了,就去找答案了。

解果答案一看才發現我的寫法跟答案差不多,唯一的差別在於:let i = functions.length; i >= 0; --i

是這一行發生了錯誤,原本的想法是想說因為functions.length 出來會比index多1,想說那我就從—i 開始執行(會有這個想法真的證明我是蠢豬),因此改成:

1
2
3
4
5
6
7
8
9
return function(x) {
let newFn = x

for (let i = functions.length -1; i >= 0; i--) {
newFn = functions[i](newFn)

}
return newFn
}

這樣就完成了

其他解法

用高階函式:reduceRight()

1
2
3
  var compose = function(functions) {
return x => functions.reduceRight((acc,f)=>f(acc),x)
};

結語

其他解法暫時還不會參考,我先把基本的學好就好了。
這次錯的地方真的很不應該,要用變數接回傳值這個明明就是很基本的操作居然忘記,最扯的還是let i = functions.length; i >= 0; --i
到底當時在想什麼--i 是更新的條件,但i還是會從functions.length 的值開始執行啊….