LeetCode 题解工作台

特殊数组 I

如果数组的每一对相邻元素都是两个奇偶性不同的数字,则该数组被认为是一个 特殊数组 。换句话说,每一对中的元素 必须 有一个是偶数,另一个是奇数。 你有一个整数数组 nums 。如果 nums 是一个 特殊数组 ,返回 true ,否则返回 false 。 示例 1: 输入: nums = [1] 输…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们从左到右遍历数组,对于每一对相邻元素,如果它们的奇偶性相同,那么数组就不是特殊数组,返回 `false`;否则,数组是特殊数组,返回 `true`。 时间复杂度 ,其中 是数组的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

如果数组的每一对相邻元素都是两个奇偶性不同的数字,则该数组被认为是一个 特殊数组。换句话说,每一对中的元素 必须 有一个是偶数,另一个是奇数。

你有一个整数数组 nums。如果 nums 是一个 特殊数组 ,返回 true,否则返回 false

 

示例 1:

输入:nums = [1]

输出:true

解释:

只有一个元素,所以答案为 true

示例 2:

输入:nums = [2,1,4]

输出:true

解释:

只有两对相邻元素: (2,1)(1,4),它们都包含了奇偶性不同的数字,因此答案为 true

示例 3:

输入:nums = [4,3,1,6]

输出:false

解释:

nums[1]nums[2] 都是奇数。因此答案为 false

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
lightbulb

解题思路

方法一:一次遍历

我们从左到右遍历数组,对于每一对相邻元素,如果它们的奇偶性相同,那么数组就不是特殊数组,返回 false;否则,数组是特殊数组,返回 true

时间复杂度 O(n)O(n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def isArraySpecial(self, nums: List[int]) -> bool:
        return all(a % 2 != b % 2 for a, b in pairwise(nums))
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks if candidate immediately handles the single-element array case.

  • question_mark

    Looks for linear scan comparing current and previous element parity.

  • question_mark

    Observes whether candidate stops early on failure, showing efficiency.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle arrays with a single element as a special array.

  • error

    Incorrectly using modulo operations leading to wrong parity comparisons.

  • error

    Not stopping early when adjacent elements have the same parity, wasting computation.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check arrays where elements must alternate between multiples of 3 and non-multiples instead of parity.

  • arrow_right_alt

    Determine if an array is special under alternating sign instead of parity.

  • arrow_right_alt

    Handle arrays of larger sizes with streaming input while preserving linear time checks.

help

常见问题

外企场景

特殊数组 I题解:数组·driven | LeetCode #3151 简单