0滑动窗口中等 LeetCode1248. 统计「优美子数组」

1248. 统计「优美子数组」

描述

给你一个整数数组 nums 和一个整数 k。如果某个连续子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。

请返回这个数组中 「优美子数组」 的数目。

分析

原理是计算k个奇数区间两端的偶数个数,然后相乘就是这个k个奇数区间的子数组个数。
在这里插入图片描述

滑动窗口遍历数组。右指针不停遍历直到奇数的个数等于k。
奇数的个数等于k,标记right的位置,然后仍然向右遍历直到走到末尾或者遇到下一个奇数,计算这段区间的个数。

class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int right = 0, left = 0, ans = 0, count = 0;
        while (right < nums.length) {
            if ((nums[right] & 1) == 1) {
                count++;
            }
            right++;
            if (count == k) {
                int tmpr = right;
                while (right < nums.length && (nums[right] & 1) == 0) {
                    right++;
                }
                int r = right - tmpr + 1;
                int tmpl = left;
                while ((nums[left] & 1) == 0) {
                    left++;
                }
                int l = left - tmpl + 1;
                ans += l * r;
                left++;
                count--;
            }
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值