leetcode

本文详细解析了LeetCode上的1248题统计优美子数组,介绍了两种算法:暴力求解和使用前缀和优化后的解决方案。通过实例解释了如何计算包含特定数量奇数的子数组。

1.leetcode-1248. 统计「优美子数组」

给你一个整数数组 nums 和一个整数 k。

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

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

输入:nums = [1,1,2,1,1], k = 3
输出:2
解释:包含 3 个奇数的子数组是 [1,1,2,1] 和 [1,2,1,1] 。

暴力求解通不过所有用例:

以begin为起点,内层循环向后遍历并计算奇数的个数,若奇数个数为k,则ans加1。begin取值[0,nums.size()-k]。

class Solution {
public:
    int numberOfSubarrays(vector<int>& nums, int k) {

        int res = 0;
    
        for (int begin = 0; begin <= nums.size() - k; ++begin) {
            
            int odd_num = 0;
            for (int i = begin; i < nums.size(); ++i) {
                if (nums[i] % 2 == 1) {
                    ++odd_num;
                }
                if (odd_num == k) {
                    ++res;
                } 
                if (odd_num > k) {//不需要继续计算次数了,因为odd_num的值已经大于k,再往后肯定还是大于k
                    break;
                }
            }
            if (odd_num < k) {//如果某次遍历出现odd_num小于k,说明以begin为起点到nums.size()区间内,没有满足条件的序列
                break;
            }
        }

        return res;
    }
};

 

使用前缀和求解:

pre[i]存[0,i]内奇数的个数,cnt存pre[i]出现的次数,只需要考虑pre[i]>=k的情况即可,比如对于测试用例,

pre为1,2,2,3,4,表示pre[0],pre[1],pre[2],pre[3],pre[4]的值.

cnt为1,1,2,1,1,表示1出现的次数为1,2出现的次数为2,3出现的次数1,4出现的次数为1(cnt[0]初值为1).

class Solution {

public:

    int numberOfSubarrays(vector<int>& nums, int k) {

        if (nums.empty()) return 0;

        vector<int> pre;

        pre.resize(nums.size(), 0);

        for (int i = 0; i < nums.size(); ++i) {

            if (i == 0) {

                pre[i] = nums[i] % 2;

                continue;

            }

            if (nums[i] % 2 == 1) {

                pre[i] = pre[i - 1] + 1;

            }

            else {

                pre[i] = pre[i - 1];

            }

        }

        int ans = 0;

        vector<int> cnt;

        cnt.resize(nums.size()+1, 0);

        cnt[0] = 1; //初值不为1会有问题

        for (int i = 0; i < nums.size(); ++i) {

            ans += pre[i] >= k ? cnt[pre[i] - k] : 0;

            ++cnt[pre[i]];

        }

        return ans;

    }

};

前缀与差分:

https://www.pianshen.com/article/7331273831/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值