LeetCode 题解工作台

转换数组中的每个元素

编写一个函数,这个函数接收一个整数数组 arr 和一个映射函数 fn ,通过该映射函数返回一个新的数组。 返回数组的创建语句应为 returnedArray[i] = fn(arr[i], i) 。 请你在不使用内置方法 Array.map 的前提下解决这个问题。 示例 1: 输入: arr = […

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · apply·transform·each·element·in·数组·core·interview·pattern

bolt

答案摘要

我们遍历数组 ,对于每个元素 ,将其替换为 $fn(arr[i], i)$。最后返回数组 即可。 时间复杂度 ,其中 为数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 apply·transform·each·element·in·数组·core·interview·pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

编写一个函数,这个函数接收一个整数数组 arr 和一个映射函数  fn ,通过该映射函数返回一个新的数组。

返回数组的创建语句应为 returnedArray[i] = fn(arr[i], i) 。

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

 

示例 1:

输入:arr = [1,2,3], fn = function plusone(n) { return n + 1; }
输出:[2,3,4]
解释: 
const newArray = map(arr, plusone); // [2,3,4]
此映射函数返回值是将数组中每个元素的值加 1。

示例 2:

输入:arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
输出:[1,3,5]
解释:此映射函数返回值根据输入数组索引增加每个值。

示例 3:

输入:arr = [10,20,30], fn = function constant() { return 42; }
输出:[42,42,42]
解释:此映射函数返回值恒为 42。

 

提示:

  • 0 <= arr.length <= 1000
  • -109 <= arr[i] <= 109
  • fn 返回一个整数。
​​​​​​
lightbulb

解题思路

方法一:遍历

我们遍历数组 arrarr,对于每个元素 arr[i]arr[i],将其替换为 fn(arr[i],i)fn(arr[i], i)。最后返回数组 arrarr 即可。

时间复杂度 O(n)O(n),其中 nn 为数组 arrarr 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
function map(arr: number[], fn: (n: number, i: number) => number): number[] {
    for (let i = 0; i < arr.length; ++i) {
        arr[i] = fn(arr[i], i);
    }
    return arr;
}
speed

复杂度分析

指标
时间complexity depends on the approach, with the loop-based solution being O(n). Space complexity also depends on the approach, typically O(n) for the new array.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can you apply the transformation manually without using Array.map?

  • question_mark

    Do you understand the role of indices in applying the transformation?

  • question_mark

    Are you able to identify edge cases like empty arrays or very large arrays?

warning

常见陷阱

外企场景
  • error

    Using Array.map instead of manually applying the transformation.

  • error

    Ignoring the index in the transformation function.

  • error

    Not handling edge cases such as an empty array or large integer values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Apply a similar transformation but with different types of functions.

  • arrow_right_alt

    Handle larger arrays with performance optimizations.

  • arrow_right_alt

    Modify the problem to return the transformed values using a different data structure.

help

常见问题

外企场景

转换数组中的每个元素题解:apply·transform·each·el… | LeetCode #2635 简单