LeetCode 题解工作台

精简对象

现给定一个对象或数组 obj ,返回一个 精简对象 。 精简对象 与原始对象相同,只是将包含 假 值的键移除。该操作适用于对象及其嵌套对象。数组被视为索引作为键的对象。当 Boolean(value) 返回 false 时,值被视为 假 值。 你可以假设 obj 是 JSON.parse 的输出结果…

category

0

题型

code_blocks

2

代码语言

hub

0

相关题

当前训练重点

中等 · Compact Object core interview pattern

bolt

答案摘要

如果 `obj` 不是对象或为空,函数会原封不动地返回,因为无需检查非对象值中的键。 如果 `obj` 是一个数组,它会使用 `obj.filter(Boolean)` 过滤掉虚假值(如 `null`、`undefined`、`false`、0、""),然后使用 `map(compactObject)` 对每个元素递归调用 `compactObject`。这样可以确保嵌套数组也被压缩。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Compact Object core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

现给定一个对象或数组 obj,返回一个 精简对象

精简对象 与原始对象相同,只是将包含 值的键移除。该操作适用于对象及其嵌套对象。数组被视为索引作为键的对象。当 Boolean(value) 返回 false 时,值被视为 值。

你可以假设 objJSON.parse 的输出结果。换句话说,它是有效的 JSON。

 

示例 1:

输入:obj = [null, 0, false, 1]
输出:[1]
解释:数组中的所有假值已被移除。

示例 2:

输入:obj = {"a": null, "b": [false, 1]}
输出:{"b": [1]}
解释:obj["a"] 和 obj["b"][0] 包含假值,因此被移除。

示例 3:

输入:obj = [null, 0, 5, [0], [false, 16]]
输出:[5, [], [16]]
解释:obj[0], obj[1], obj[3][0], 和 obj[4][0] 包含假值,因此被移除。

 

提示:

  • obj 是一个有效的 JSON 对象
  • 2 <= JSON.stringify(obj).length <= 106
lightbulb

解题思路

方法一:递归

如果 obj 不是对象或为空,函数会原封不动地返回,因为无需检查非对象值中的键。

如果 obj 是一个数组,它会使用 obj.filter(Boolean) 过滤掉虚假值(如 nullundefinedfalse、0、""),然后使用 map(compactObject) 对每个元素递归调用 compactObject。这样可以确保嵌套数组也被压缩。

如果 obj 是一个对象,则会创建一个新的空对象 compactedObj。它会遍历 obj 的所有键,并对每个键在相应的值上递归调用 compactObject,然后将结果存储在值变量中。如果值是真实的(即不是虚假的),它就会将其赋值给具有相应键的压缩对象。

时间复杂度 O(n)O(n), 空间复杂度 O(n)O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * @param {Object|Array} obj
 * @return {Object|Array}
 */
var compactObject = function (obj) {
    if (!obj || typeof obj !== 'object') {
        return obj;
    }
    if (Array.isArray(obj)) {
        return obj.filter(Boolean).map(compactObject);
    }
    return Object.entries(obj).reduce((acc, [key, value]) => {
        if (value) {
            acc[key] = compactObject(value);
        }
        return acc;
    }, {});
};
speed

复杂度分析

指标
时间complexity is O(N) since each element is visited once. Space complexity is O(N) due to recursion and constructing the new compacted structure, proportional to the number of truthy elements.
空间O(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect recursive traversal or iterative stack solutions for nested objects.

  • question_mark

    Look for handling arrays as objects to ensure correct index compaction.

  • question_mark

    Watch for correct identification of all falsy values, including 0 and empty strings.

warning

常见陷阱

外企场景
  • error

    Failing to recurse into nested arrays or objects and leaving falsy values.

  • error

    Removing array elements incorrectly, breaking the original order.

  • error

    Misidentifying truthy and falsy values, leading to incorrect output.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compact only top-level keys without recursion for a simpler version.

  • arrow_right_alt

    Compact objects but keep arrays intact, testing selective recursion.

  • arrow_right_alt

    Compact and also sort keys or array elements after filtering for deterministic output.

help

常见问题

外企场景

精简对象题解:Compact Object core int… | LeetCode #2705 中等