Given an integer array arr
, return true
if there are three consecutive odd numbers in the array. Otherwise, return false
.
给定一个整数数组arr,如果数组中有三个连续的奇数,则返回true。否则,返回false。
Example 1:
Input: arr = [2,6,4,1] Output: false Explanation: There are no three consecutive odds.
Example 2:
Input: arr = [1,2,34,3,4,5,7,23,12] Output: true Explanation: [5,7,23] are three consecutive odds.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
Idea:
Idea is simple, use a number numberOfConsecutiveOdds to keep the numbers of three consecutive odd numbers in the array, if numberOfConsecutiveOdds is three, return true. When meet an even number, let numberOfConsecutiveOdds equals to 0 and restart the count. When meet a odd number, add 1 to numberOfConsecutiveOdds
想法很简单,使用一个数字numberOfConsecutiveOdds来保持三个连续奇数的数字在数组中,如果numberOfConsecutiveOdds是3,返回true。当遇到偶数时,让numberOfConsecutiveOdds等于0并重新开始计数。当遇到一个奇数时,将numberOfConsecutiveOdds 加1
func threeConsecutiveOdds(_ arr: [Int]) -> Bool {
var numberOfConsecutiveOdds = 0
for (_,number) in arr.enumerated(){
if numberOfConsecutiveOdds == 3{
return true
}
else if number % 2 != 0 {
numberOfConsecutiveOdds += 1
}
else{
numberOfConsecutiveOdds = 0
}
}
return numberOfConsecutiveOdds == 3 ? true : false
}