题目描述

解法
设置一个变量temp,当累计到3时跳出循环。时间复杂度O(n)O(n)O(n),空间复杂度O(1)O(1)O(1)。
Python代码:
class Solution:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
temp = 0
isFound = False
for i in range(len(arr)):
if arr[i] % 2 != 0:
temp += 1
if temp == 3:
isFound = True
break
else:
temp = 0
return isFound
C++代码:
class Solution {
public:
bool threeConsecutiveOdds(vector<int>& arr) {
int temp = 0;
bool isFound = false;
for(int i=0;i<arr.size();i++){
if(arr[i] % 2 != 0){
temp++;
if(temp == 3){
isFound = true;
break;
}
}else{
temp = 0;
}
}
return isFound;
}
};

本文介绍了一种使用Python和C++实现的算法,用于检测数组中是否存在三个连续的奇数。通过设置一个计数器变量,该算法可以有效地在O(n)的时间复杂度和O(1)的空间复杂度下完成任务。
- LeetCode&spm=1001.2101.3001.5002&articleId=108238571&d=1&t=3&u=6eb899268e0e487f9820ef9a20302b5f)
1109

被折叠的 条评论
为什么被折叠?



