LeetCode 题解工作台

数组归约运算

给定一个整数数组 nums 、一个 reducer 函数 fn 和一个初始值 init ,返回通过依次对数组的每个元素执行 fn 函数得到的最终结果。 通过以下操作实现这个结果: val = fn(init, nums[0]),val = fn(val, nums[1]),val = fn(val,…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · 数组·reduce·transformation·core·interview·pattern

bolt

答案摘要

type Fn = (accum: number, curr: number) => number; function reduce(nums: number[], fn: Fn, init: number): number {

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·reduce·transformation·core·interview·pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数数组 nums、一个 reducer 函数 fn 和一个初始值 init,返回通过依次对数组的每个元素执行 fn 函数得到的最终结果。

通过以下操作实现这个结果:val = fn(init, nums[0]),val = fn(val, nums[1]),val = fn(val, nums[2]),... 直到处理数组中的每个元素。然后返回 val 的最终值。

如果数组的长度为 0,则函数应返回 init

请你在不使用内置数组方法的 Array.reduce 前提下解决这个问题。

 

示例 1:

输入:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
输出:10
解释:
初始值为 init=0 。
(0) + nums[0] = 1
(1) + nums[1] = 3
(3) + nums[2] = 6
(6) + nums[3] = 10
Val 最终值为 10。

示例 2:

输入: 
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
输出:130
解释:
初始值为 init=100 。
(100) + nums[0]^2 = 101
(101) + nums[1]^2 = 105
(105) + nums[2]^2 = 114
(114) + nums[3]^2 = 130
Val 最终值为 130。

示例3:

输入: 
nums = []
fn = function sum(accum, curr) { return 0; }
init = 25
输出:25
解释:这是一个空数组,所以返回 init 。

 

提示:

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • 0 <= init <= 1000
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
type Fn = (accum: number, curr: number) => number;

function reduce(nums: number[], fn: Fn, init: number): number {
    let acc: number = init;
    for (const x of nums) {
        acc = fn(acc, x);
    }
    return acc;
}
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of sequential operations and the effect of passing intermediate results to the reducer function.

  • question_mark

    Test if the candidate accounts for edge cases like empty arrays properly.

  • question_mark

    Observe if the candidate can explain the time and space complexities effectively.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle empty arrays and returning the correct initial value.

  • error

    Not correctly passing the updated value from one iteration to the next.

  • error

    Misunderstanding the reducer function’s behavior and applying it incorrectly to elements.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Introduce variations where the reducer function performs operations like subtraction or multiplication instead of addition.

  • arrow_right_alt

    Test cases with arrays containing negative numbers to ensure correctness in all cases.

  • arrow_right_alt

    Consider reducing objects or more complex data types instead of just numbers.

help

常见问题

外企场景

数组归约运算题解:数组·reduce·transformatio… | LeetCode #2626 简单