LeetCode 题解工作台

判断对象是否为空

给定一个对象或数组,判断它是否为空。 一个空对象不包含任何键值对。 一个空数组不包含任何元素。 你可以假设对象或数组是通过 JSON.parse 解析得到的。 示例 1: 输入: obj = {"x": 5, "y": 42} 输出: false 解释: 这个对象有两个键值对,所以它不为空。 示例 …

category

0

题型

code_blocks

2

代码语言

hub

0

相关题

当前训练重点

简单 · Is Object Empty core interview pattern

bolt

答案摘要

我们可以遍历对象或数组,如果遍历到了第一个元素,就返回 `false`,否则返回 `true`。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个对象或数组,判断它是否为空。

  • 一个空对象不包含任何键值对。
  • 一个空数组不包含任何元素。

你可以假设对象或数组是通过 JSON.parse 解析得到的。

 

示例 1:

输入:obj = {"x": 5, "y": 42}
输出:false
解释:这个对象有两个键值对,所以它不为空。

示例 2:

输入:obj = {}
输出:true
解释:这个对象没有任何键值对,所以它为空。

示例 3:

输入:obj = [null, false, 0]
输出:false
解释:这个数组有 3 个元素,所以它不为空。

 

提示:

  • obj 是一个有效的 JSON 对象或数组
  • 2 <= JSON.stringify(obj).length <= 105

 

你可以在 O(1) 时间复杂度内解决这个问题吗?
lightbulb

解题思路

方法一:遍历

我们可以遍历对象或数组,如果遍历到了第一个元素,就返回 false,否则返回 true

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

1
2
3
4
5
6
7
8
9
10
11
/**
 * @param {Object | Array} obj
 * @return {boolean}
 */
var isEmpty = function (obj) {
    for (const x in obj) {
        return false;
    }
    return true;
};
speed

复杂度分析

指标
时间complexity is O(1) for checking array length and O(n) for object keys with n properties. Space complexity is O(n) if Object.keys creates a new array of keys.
空间**
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect candidates to differentiate between objects and arrays.

  • question_mark

    Watch for solutions that manually iterate instead of using built-in properties.

  • question_mark

    Check that candidates handle empty and non-empty cases correctly.

warning

常见陷阱

外企场景
  • error

    Assuming empty objects and arrays are the same without type check.

  • error

    Iterating unnecessarily over object keys instead of checking length.

  • error

    Returning incorrect values for falsy elements in arrays like 0 or null.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check nested objects for emptiness recursively.

  • arrow_right_alt

    Determine emptiness for objects containing only empty arrays or objects.

  • arrow_right_alt

    Return a count of non-empty elements instead of a boolean.

help

常见问题

外企场景

判断对象是否为空题解:Is Object Empty core in… | LeetCode #2727 简单