一站多通怎么做网站,网站推广工具 刷链接,公司发展规划,做任务推广网站给你一个下标从 0 开始的整数数组 nums 和一个整数 threshold 。
请你从 nums 的子数组中找出以下标 l 开头、下标 r 结尾 (0 l r nums.length) 且满足以下条件的 最长子数组 #xff1a;
nums[l] % 2 0对于范围 [l, r - 1] 内的所有下标 i #xff0c;num…给你一个下标从 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 是满足题目要求的最大长度。示例 3
输入nums [2,3,4,5], threshold 4
输出3
解释
在这个示例中我们选择从 l 0 开始、到 r 2 结束的子数组 [2,3,4] 。
该子数组满足上述全部条件。
因此答案就是这个子数组的长度 3 。可以证明 3 是满足题目要求的最大长度。提示
1 nums.length 100 1 nums[i] 100 1 threshold 100
//分组循环
class Solution {public int longestAlternatingSubarray(int[] nums, int threshold) {int n nums.length;int ans 0, i 0;while (i n) {if (nums[i] threshold || nums[i] % 2 ! 0) {i; // 直接跳过continue;}int start i; // 记录这一组的开始位置i; // 开始位置已经满足要求从下一个位置开始判断while (i n nums[i] threshold nums[i] % 2 ! nums[i - 1] % 2) {i;}// 从 start 到 i-1 是满足题目要求的并且无法再延长的子数组ans Math.max(ans, i - start);}return ans;}
}