LeetCode 题解工作台
复合函数
请你编写一个函数,它接收一个函数数组 [f 1 , f 2 , f 3 ,…, f n ] ,并返回一个新的函数 fn ,它是函数数组的 复合函数 。 [f(x), g(x), h(x)] 的 复合函数 为 fn(x) = f(g(h(x))) 。 一个空函数列表的 复合函数 是 恒等函数 f(x)…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Function Composition core interview pattern
答案摘要
type F = (x: number) => number; function compose(functions: F[]): F {
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Function Composition core interview pattern 题型思路
题目描述
请你编写一个函数,它接收一个函数数组 [f1, f2, f3,…, fn] ,并返回一个新的函数 fn ,它是函数数组的 复合函数 。
[f(x), g(x), h(x)] 的 复合函数 为 fn(x) = f(g(h(x))) 。
一个空函数列表的 复合函数 是 恒等函数 f(x) = x 。
你可以假设数组中的每个函数接受一个整型参数作为输入,并返回一个整型作为输出。
示例 1:
输入:functions = [x => x + 1, x => x * x, x => 2 * x], x = 4 输出:65 解释: 从右向左计算...... Starting with x = 4. 2 * (4) = 8 (8) * (8) = 64 (64) + 1 = 65
示例 2:
输入:functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1 输出:1000 解释: 从右向左计算...... 10 * (1) = 10 10 * (10) = 100 10 * (100) = 1000
示例 3:
输入:functions = [], x = 42 输出:42 解释: 空函数列表的复合函数就是恒等函数
提示:
-1000 <= x <= 10000 <= functions.length <= 1000- 所有函数都接受并返回一个整型
解题思路
方法一
type F = (x: number) => number;
function compose(functions: F[]): F {
return function (x) {
return functions.reduceRight((acc, fn) => fn(acc), x);
};
}
/**
* const fn = compose([x => x + 1, x => 2 * x])
* fn(4) // 9
*/
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) per function call where n is the number of functions, since each function is applied once. Space complexity is O(1) additional space if implemented iteratively, or O(n) if using recursion due to call stack. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for correct right-to-left application of functions.
- question_mark
Check if the candidate handles empty arrays as identity functions.
- question_mark
Verify that each function is called exactly once in order.
常见陷阱
外企场景- error
Applying functions from left to right instead of right to left.
- error
Not returning a function, which breaks the composition pattern.
- error
Failing to handle empty arrays, causing runtime errors.
进阶变体
外企场景- arrow_right_alt
Compose functions that accept multiple arguments instead of a single integer.
- arrow_right_alt
Compose asynchronous functions returning promises for functional chaining.
- arrow_right_alt
Optimize composition by reducing repeated calls for idempotent functions.