当前位置:网站首页>Leetcode 1248. Statistics of "graceful subarray" (harm, suddenly found that it can only enumerate violently)

Leetcode 1248. Statistics of "graceful subarray" (harm, suddenly found that it can only enumerate violently)

2022-06-25 00:57:00 I'm not xiaohaiwa~~~~

Give you an array of integers nums And an integer k. If there happens to be... In a continuous subarray k It's an odd number , We think that this subarray is 「 Graceful subarray 」.

Please return to this array 「 Graceful subarray 」 Number of .

Example 1:

 Input :nums = [1,1,2,1,1], k = 3
 Output :2
 explain : contain  3  An odd subarray is  [1,1,2,1]  and  [1,2,1,1] .

Example 2:

 Input :nums = [2,4,6], k = 1
 Output :0
 explain : There are no odd numbers in the sequence , So there's no graceful subarray .

Example 3:

 Input :nums = [2,2,2,1,2,2,1,2,2,2], k = 2
 Output :16

Tips :

  • 1 <= nums.length <= 50000
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= nums.length

Code:

class Solution {
    
public:
    int numberOfSubarrays(vector<int>& nums, int k) {
    
        
        int res=0;
        for(int i=0;i<nums.size();i++)
        {
    
            int cnt=0;
            for(int j=i;j<nums.size();j++)
            {
    
                if(nums[j]%2)
                {
    
                    cnt++;
                }
                if(cnt>k)
                {
    
                    break;
                }
                if(cnt==k)
                {
    
                    res++;
                }
            }
        }
        cout<<res<<endl;
        return res;
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206242008518048.html