LeetCode 题解工作台
判断对象是否为空
给定一个对象或数组,判断它是否为空。 一个空对象不包含任何键值对。 一个空数组不包含任何元素。 你可以假设对象或数组是通过 JSON.parse 解析得到的。 示例 1: 输入: obj = {"x": 5, "y": 42} 输出: false 解释: 这个对象有两个键值对,所以它不为空。 示例 …
0
题型
2
代码语言
0
相关题
当前训练重点
简单 · Is Object Empty core interview pattern
答案摘要
我们可以遍历对象或数组,如果遍历到了第一个元素,就返回 `false`,否则返回 `true`。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Is Object Empty core interview pattern 题型思路
题目描述
给定一个对象或数组,判断它是否为空。
- 一个空对象不包含任何键值对。
- 一个空数组不包含任何元素。
你可以假设对象或数组是通过 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) 时间复杂度内解决这个问题吗?
解题思路
方法一:遍历
我们可以遍历对象或数组,如果遍历到了第一个元素,就返回 false,否则返回 true。
时间复杂度 ,空间复杂度 。
/**
* @param {Object | Array} obj
* @return {boolean}
*/
var isEmpty = function (obj) {
for (const x in obj) {
return false;
}
return true;
};
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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. |
| 空间 | ** |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.