LeetCode 题解工作台

存在连续三个奇数的数组

给你一个整数数组 arr ,请你判断数组中是否存在连续三个元素都是奇数的情况:如果存在,请返回 true ;否则,返回 false 。 示例 1: 输入: arr = [2,6,4,1] 输出: false 解释: 不存在连续三个元素都是奇数的情况。 示例 2: 输入: arr = [1,2,34,…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们用一个变量 记录当前连续奇数的个数。 接下来,我们遍历数组,如果当前元素是奇数,则 加一,如果 等于 3,则返回 。如果当前元素是偶数,则 置零。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 arr,请你判断数组中是否存在连续三个元素都是奇数的情况:如果存在,请返回 true ;否则,返回 false

 

示例 1:

输入:arr = [2,6,4,1]
输出:false
解释:不存在连续三个元素都是奇数的情况。

示例 2:

输入:arr = [1,2,34,3,4,5,7,23,12]
输出:true
解释:存在连续三个元素都是奇数的情况,即 [5,7,23] 。

 

提示:

  • 1 <= arr.length <= 1000
  • 1 <= arr[i] <= 1000
lightbulb

解题思路

方法一:遍历 + 计数

我们用一个变量 cnt\textit{cnt} 记录当前连续奇数的个数。

接下来,我们遍历数组,如果当前元素是奇数,则 cnt\textit{cnt} 加一,如果 cnt\textit{cnt} 等于 3,则返回 True\textit{True}。如果当前元素是偶数,则 cnt\textit{cnt} 置零。

遍历结束后,如果没有找到连续三个奇数,则返回 False\textit{False}

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

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def threeConsecutiveOdds(self, arr: List[int]) -> bool:
        cnt = 0
        for x in arr:
            if x & 1:
                cnt += 1
                if cnt == 3:
                    return True
            else:
                cnt = 0
        return False
speed

复杂度分析

指标
时间complexity is O(n) because each element is checked once for parity. Space complexity is O(1) since only a single counter variable is maintained regardless of array size.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for early return opportunities when consecutive odd count reaches three.

  • question_mark

    Emphasize a simple linear scan instead of nested loops or extra arrays.

  • question_mark

    Expect you to handle all edge cases, like arrays shorter than three elements.

warning

常见陷阱

外企场景
  • error

    Resetting the consecutive odd counter incorrectly when encountering even numbers.

  • error

    Using additional arrays unnecessarily instead of a single counter.

  • error

    Failing to account for arrays with exactly three elements or fewer.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check for k consecutive odd numbers instead of exactly three, adjusting the counter threshold.

  • arrow_right_alt

    Detect three consecutive even numbers using the same array-driven parity strategy.

  • arrow_right_alt

    Count the number of segments with three consecutive odds instead of just returning a boolean.

help

常见问题

外企场景

存在连续三个奇数的数组题解:数组·driven | LeetCode #1550 简单