【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和我的個人博客,原創不易,轉載經作者同意后請附上原文鏈接哦~
千篇源碼題解已開源