题目要求
给你一个整数数组 array,请你判断数组中是否存在连续三个元素都是奇数的情况:如果存在,请返回 true;否则,返回 false 。
示例 1:
输入:array = [2,6,4,1] 输出:false
解释:不存在连续三个元素都是奇数的情况。
示例 2:
输入:array = [1,2,34,3,4,5,7,23,12]输出:true
解释:存在连续三个元素都是奇数的情况,即 [5,7,23] 。
力扣原题
https://leetcode.cn/problems/three-consecutive-odds/description/
实现代码
public class Main {
public static boolean threeConsecutiveOdds(int[] array) {
int count = 0;//计数器
for (int i : array) {
if (i % 2 != 0) {
count++;
if (count == 3) {
return true;
}
} else {
//如果没有重新赋值为0,则为判断数组中有没有三个奇数(不是连续的)
count = 0;
}
}
return false;
}
public static void main(String[] args) {
int[] array = {1, 2, 34, 3, 4, 5, 7, 23, 12};
System.out.println(threeConsecutiveOdds(array));
}
}
输出结果
true
觉得写的不错的话点个赞呗😊