LeetCode 1550.存在连续三个奇数的数组:遍历
【LetMeFly】1550.存在连续三个奇数的数组:遍历
力扣题目链接:https://leetcode.cn/problems/three-consecutive-odds/
给你一个整数数组 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
解题方法:遍历
从第3个元素(下标2)开始向后遍历,若遇到连续3个奇数则直接返回true,否则返回false。
- 时间复杂度 O ( l e n ( n u m s ) ) O(len(nums)) O(len(nums))
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
/** @Author: LetMeFly* @Date: 2025-05-11 14:00:52* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-05-11 14:13:46*/
class Solution {
public:bool threeConsecutiveOdds(vector<int>& arr) {for (int i = 2; i < arr.size(); i++) {if (arr[i] % 2 && arr[i - 1] % 2 && arr[i - 2] % 2) {return true;}}return false;}
};
Python
'''
Author: LetMeFly
Date: 2025-05-11 14:00:52
LastEditors: LetMeFly.xyz
LastEditTime: 2025-05-11 14:16:01
Description: AC,100.00%,93.48%
'''
from typing import Listclass Solution:def threeConsecutiveOdds(self, arr: List[int]) -> bool:for i in range(2, len(arr)):if arr[i] % 2 and arr[i - 1] % 2 and arr[i - 2] % 2:return Truereturn False
Java
/** @Author: LetMeFly* @Date: 2025-05-11 14:00:52* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-05-11 14:17:39* @Description: 1550: AC,100.00%,88.19%*/
class Solution {public boolean threeConsecutiveOdds(int[] arr) {for (int i = 2; i < arr.length; i++) {if (arr[i] % 2 == 1 && arr[i - 1] % 2 == 1 && arr[i - 2] % 2 == 1) {return true;}}return false;}
}
Go
/** @Author: LetMeFly* @Date: 2025-05-11 14:00:52* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-05-11 14:19:31*/
package mainfunc threeConsecutiveOdds(arr []int) bool {for i := 2; i < len(arr); i++ {if arr[i] % 2 == 1 && arr[i - 1] % 2 == 1 && arr[i - 2] % 2 == 1 {return true}}return false;
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源