LeetCode 题解工作台

过滤数组中的元素

给定一个整数数组 arr 和一个过滤函数 fn ,并返回一个过滤后的数组 filteredArr 。 fn 函数接受一个或两个参数: arr[i] - arr 中的数字 i - arr[i] 的索引 filteredArr 应该只包含使表达式 fn(arr[i], i) 的值为 真值 的 arr 中…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

简单 · filter·elements·from·数组·core·interview·pattern

bolt

答案摘要

我们遍历数组 ,对于每个元素 ,如果 $fn(arr[i], i)$ 为真,则将其加入答案数组中。最后返回答案数组即可。 时间复杂度 ,其中 为数组 的长度。忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数数组 arr 和一个过滤函数 fn,并返回一个过滤后的数组 filteredArr

fn 函数接受一个或两个参数:

  • arr[i] - arr 中的数字
  • i - arr[i] 的索引

filteredArr 应该只包含使表达式 fn(arr[i], i) 的值为 真值arr 中的元素。真值 是指 Boolean(value) 返回参数为 true 的值。

请在不使用内置的 Array.filter 方法的情况下解决该问题。

 

示例 1:

输入:arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
输出: [20,30]
解释:
const newArray = filter(arr, fn); // [20, 30]
过滤函数过滤掉不大于 10 的值

示例 2:

输入:arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
输出:[1]
解释:
过滤函数 fn 也可以接受每个元素的索引
在这种情况下,过滤函数删除索引不为 0 的元素

示例 3:

输入:arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
输出:[-2,0,1,2]
解释:
像 0 这样的假值应被过滤掉

 

提示:

  • 0 <= arr.length <= 1000
  • -109 <= arr[i] <= 109
lightbulb

解题思路

方法一:遍历

我们遍历数组 arrarr,对于每个元素 arr[i]arr[i],如果 fn(arr[i],i)fn(arr[i], i) 为真,则将其加入答案数组中。最后返回答案数组即可。

时间复杂度 O(n)O(n),其中 nn 为数组 arrarr 的长度。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
function filter(arr: number[], fn: (n: number, i: number) => any): number[] {
    const ans: number[] = [];
    for (let i = 0; i < arr.length; ++i) {
        if (fn(arr[i], i)) {
            ans.push(arr[i]);
        }
    }
    return ans;
}
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Tests knowledge of JavaScript's `filter()` method and custom function behavior.

  • question_mark

    Checks understanding of handling edge cases like empty arrays or non-truthy values.

  • question_mark

    Evaluates ability to apply filtering criteria efficiently based on different inputs.

warning

常见陷阱

外企场景
  • error

    Not handling edge cases like an empty array or invalid return values from the filtering function.

  • error

    Assuming the `fn` function can only handle values without considering indices.

  • error

    Returning incorrect results due to misunderstanding what constitutes a truthy value in JavaScript.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Filter based on both value and index.

  • arrow_right_alt

    Apply filtering logic to a multidimensional array.

  • arrow_right_alt

    Use custom filtering functions instead of predefined ones.

help

常见问题

外企场景

过滤数组中的元素题解:filter·elements·from·数组… | LeetCode #2634 简单