2629. 复合函数
2629. 复合函数
题目
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.
Example 1:
Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4
Output: 65
Explanation:
Evaluating from right to left ...
Starting with x = 4.
2 * (4) = 8
(8) * (8) = 64
(64) + 1 = 65
Example 2:
Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1
Output: 1000
Explanation:
Evaluating from right to left ...
10 * (1) = 10
10 * (10) = 100
10 * (100) = 1000
Example 3:
Input: functions = [], x = 42
Output: 42
Explanation:
The composition of zero functions is the identity function
Constraints:
-1000 <= x <= 10000 <= functions.length <= 1000- all functions accept and return a single integer
题目大意
请你编写一个函数,它接收一个函数数组 [f1, f2, f3,…, fn] ,并返回一个新的函数 fn ,它是函数数组的 复合函数 。
[f(x), g(x), h(x)] 的 复合函数 为 fn(x) = f(g(h(x))) 。
一个空函数列表的 复合函数 是 恒等函数 f(x) = x 。
你可以假设数组中的每个函数接受一个整型参数作为输入,并返回一个整型作为输出。
提示:
-1000 <= x <= 10000 <= functions.length <= 1000- 所有函数都接受并返回一个整型
解题思路
这道题要将多个函数按照从右到左的顺序嵌套执行,核心在于理解函数组合的执行顺序以及如何在 JavaScript 中使用 reduceRight 来简化实现。
- 从右向左执行函数:需要对输入值依次应用函数数组中的函数,从最后一个函数开始,依次向前应用,这可以使用
reduceRight来实现。 - 空数组情况:如果函数数组为空,返回的应该是一个恒等函数,也就是
return x => x,因为没有任何操作需要执行。
复杂度分析
- 时间复杂度:
O(n),其中n是functions数组的长度,需要对数组中的每一个函数执行一次调用。 - 空间复杂度:
O(1),除了输入和输出的额外空间,不需要额外的空间存储其他数据。
代码
/**
* @param {Function[]} functions
* @return {Function}
*/
var compose = function (functions) {
return function (x) {
return functions.reduceRight((acc, fn) => fn(acc), x);
};
};
/**
* const fn = compose([x => x + 1, x => 2 * x])
* fn(4) // 9
*/
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 2620 | 计数器 | [✓] | 🟢 | 🀄️ 🔗 | |
| 2623 | 记忆函数 | [✓] | 🟠 | 🀄️ 🔗 |
