LeetCode 题解工作台
存在连续三个奇数的数组
给你一个整数数组 arr ,请你判断数组中是否存在连续三个元素都是奇数的情况:如果存在,请返回 true ;否则,返回 false 。 示例 1: 输入: arr = [2,6,4,1] 输出: false 解释: 不存在连续三个元素都是奇数的情况。 示例 2: 输入: arr = [1,2,34,…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们用一个变量 记录当前连续奇数的个数。 接下来,我们遍历数组,如果当前元素是奇数,则 加一,如果 等于 3,则返回 。如果当前元素是偶数,则 置零。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个整数数组 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 <= 10001 <= arr[i] <= 1000
解题思路
方法一:遍历 + 计数
我们用一个变量 记录当前连续奇数的个数。
接下来,我们遍历数组,如果当前元素是奇数,则 加一,如果 等于 3,则返回 。如果当前元素是偶数,则 置零。
遍历结束后,如果没有找到连续三个奇数,则返回 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.