LeetCode 1248 Count Number of Nice Subarrays (哈希 推荐)

Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.

Return the number of nice sub-arrays.

Example 1:

Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].

Example 2:

Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.

Example 3:

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

Constraints:

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

题目链接:https://leetcode.com/problems/count-number-of-nice-subarrays/

题目大意:求包含k个奇数的子数组个数

题目分析:用一个数组pos记录奇数数字的下标,对每个奇数分别累计其左边和右边有多少个偶数记为数组l0和r0,接着枚举计算即可,对第i个奇数和第i+k-1个奇数,他们能构成的长度为k的子数组为(1+l0[pos[i]]) * (1 + r0[pos[i+k-1]]) 

12ms,时间击败81.3%

class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int n = nums.length, sum = 0;
        int[] pos = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            if (nums[i - 1] % 2 == 1) {
                pos[++sum] = i;
            }
        }

        int[] r0 = new int[n + 1];
        int cntr0 = 0;
        for (int i = n; i >= 1; i--) {
            if (nums[i - 1] % 2 == 0) {
                cntr0++;
            } else {
                r0[i] = cntr0;
                cntr0 = 0;
            }
        }
            
        int[] l0 = new int[n + 1];
        int cntl0 = 0;
        for (int i = 1; i <= n; i++) {
            if (nums[i - 1] % 2 == 0) {
                cntl0++;
            } else {
                l0[i] = cntl0;
                cntl0 = 0;
            }
        }
        int ans = 0;
        for (int i = 1; i + k - 1 <= sum; i++) {
            if (pos[i] != 0 && i + k - 1 <= sum && pos[i + k - 1] != 0) {
                ans += (1 + l0[pos[i]]) * (1 + r0[pos[i + k - 1]]);
            }
        }
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值