Skip to content

Latest commit

 

History

History
78 lines (53 loc) · 1.84 KB

File metadata and controls

78 lines (53 loc) · 1.84 KB

English Version

题目描述

Given an object or an array, return if it is empty.

  • An empty object contains no key-value pairs.
  • An empty array contains no elements.

You may assume the object or array is the output of JSON.parse.

 

Example 1:

Input: obj = {"x": 5, "y": 42}
Output: false
Explanation: The object has 2 key-value pairs so it is not empty.

Example 2:

Input: obj = {}
Output: true
Explanation: The object doesn't have any key-value pairs so it is empty.

Example 3:

Input: obj = [null, false, 0]
Output: false
Explanation: The array has 3 elements so it is not empty.

 

Constraints:

  •  2 <= JSON.stringify(obj).length <= 105

 

Can you solve it in O(1) time?

解法

方法一:遍历

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

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

TypeScript

function isEmpty(obj: Record<string, any> | any[]): boolean {
    for (const x in obj) {
        return false;
    }
    return true;
}