给你一个下标从 0 开始的整数数组 nums
和一个整数 threshold
。
请你从 nums
的子数组中找出以下标 l
开头、下标 r
结尾 (0 <= l <= r < nums.length)
且满足以下条件的 最长子数组 :
nums[l] % 2 == 0
- 对于范围
[l, r - 1]
内的所有下标i
,nums[i] % 2 != nums[i + 1] % 2
- 对于范围
[l, r]
内的所有下标i
,nums[i] <= threshold
以整数形式返回满足题目要求的最长子数组的长度。
注意:子数组 是数组中的一个连续非空元素序列。
示例 1:
输入:nums = [3,2,5,4], threshold = 5 输出:3 解释:在这个示例中,我们选择从 l = 1 开始、到 r = 3 结束的子数组 => [2,5,4] ,满足上述条件。 因此,答案就是这个子数组的长度 3 。可以证明 3 是满足题目要求的最大长度。
示例 2:
输入:nums = [1,2], threshold = 2 输出:1 解释:在这个示例中,我们选择从 l = 1 开始、到 r = 1 结束的子数组 => [2] 。 该子数组满足上述全部条件。可以证明 1 是满足题目要求的最大长度。
class Solution {
public int longestAlternatingSubarray(int[] nums, int threshold) {
int count = 0;//子串长度(中间变量)
int ans = 0;//最长奇偶数组长度
int temp = 0;//奇偶数标记('0'表示偶数,'1'表示奇数)
for(int i = 0; i < nums.length; i++){
if(nums[i] % 2 == 0 && nums[i] <= threshold){//该数字是偶数,且 <= threshould
if(temp == 0){//表示该位置是偶数
count++;
temp = 1;//下一个数字是奇数
}else{//该位置不是偶数,如(2,2)这种连续偶数
ans = Math.max(ans,count);
count = 1;//从第二个'2'开始,所以初始化子串长度为1
}
}else if(nums[i] % 2 != 0 && nums[i] <= threshold){//该数字是奇数,且 <= threshould
if(temp == 1){//表示该位置是奇数
count++;
temp = 0;//更新temp,下一个数字为偶数
}else{//该位置不是奇数,如(2,3,3)这种连续奇数
ans = Math.max(ans,count);
count = 0;//因为要求开头必须是偶数,所以子串长度从0开始
}
}else{//表示该数字 >= threshould
temp = 0;
ans = Math.max(ans,count);
count = 0;
}//表示遍历完数组,获得最长奇偶数组
if(i == nums.length - 1){
ans = Math.max(ans,count);
}
}
return ans;
}
}