给你一个整数数组 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/three-consecutive-odds
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
package cn.fansunion.leecode.isNumber;
/**
* 1550. 存在连续三个奇数的数组 给你一个整数数组 arr,请你判断数组中是否存在连续三个元素都是奇数的情况:<br/>
* 如果存在,请返回 true ;否则,返回 false 。
* 力扣
* @author [email protected]
*
* 2022-2-19
*/
public class ThreeConsecutiveOdds {
/* 示例 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,满足条件。
*
* @param arr
* @return
*/
public boolean threeConsecutiveOdds(int[] arr) {
if (arr == null || arr.length < 3) {
return false;
}
// 连续奇数的总数量
int continuousOddSize = 0;
for (int index = 0; index < arr.length; index++) {
if (arr[index] % 2 == 1) {
continuousOddSize++;
if (continuousOddSize == 3) {
return true;
}
} else {
// 遇到偶数,清零
continuousOddSize = 0;
}
}
return false;
}
}
package test.leecode.isNumber;标签:arr,奇数,3618,Assert,int,threeConsecutiveOdds,数组,pn From: https://blog.51cto.com/fansunion/6056780
import org.junit.Assert;
import org.junit.Test;
import cn.fansunion.leecode.isNumber.ThreeConsecutiveOdds;
/**
*
* @author [email protected]
*
* 2022-2-22
*/
public class ThreeConsecutiveOddsTest {
@Test
public void test() {
ThreeConsecutiveOdds pn = new ThreeConsecutiveOdds();
Assert.assertTrue(pn.threeConsecutiveOdds(new int[] {1, 2, 3, 4, 5, 6, 11, 13, 15, 23, 29}));
Assert.assertTrue(pn.threeConsecutiveOdds(new int[] {1, 2, 3, 4, 5, 6, 11, 13, 23, 29}));
Assert.assertTrue(pn.threeConsecutiveOdds(new int[] {1, 1, 3, 4, 5, 6, 11, 12, 22, 22}));
Assert.assertTrue(pn.threeConsecutiveOdds(new int[] {1, 101, 1003, 1115, 8, 6, 11, 12, 22, 22}));
Assert.assertFalse(pn.threeConsecutiveOdds(new int[] {1, 2, 3, 4, 5, 6, 11, 13, 22, 29}));
Assert.assertFalse(pn.threeConsecutiveOdds(new int[] {1, 2, 2, 4, 5, 6, 11, 12, 29, 29}));
}
}