LintCode 1258 · Beautiful Subarrays (前缀和好题)

1258 · Beautiful Subarrays
Algorithms
Medium
Description
A beautiful subarray is defined as an array of any length having a specific number of odd elements. Given an array of integers and a number of odd elements that constitutes beauty, create as many distinct beautiful subarrays as possible. Distinct means the arrays do not share identical starting and ending indices, though they may share one of the two. Return the number of beautiful subarrays.

the length of nums is within range: [1, 100000]
numOdds is with range: [1, 100000]
Guarantee the type of result is int.
Example
Example 1:
Input:
nums = [1, 2, 3, 4, 5]
numOdds = 2
Output: 4
Explanation: There are 4 subarrays only have two odds. such as: [1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5].
Example 2:
Input:
nums = [2, 4, 6, 8]
numOdds = 1
Output: 0
Explanation: No odd number in array

解法1:类似presum。参考的网上的答案。这里的odd就是迄今为止的奇数的累计个数。count[odd] 就表示有多少个下标满足这个odd。当odd>=numOdds后,每次加上count[odd-numOdds]就可以了。

class Solution {
public:
    /**
     * @param nums: an integer list
     * @param numOdds: an integer
     * @return: return the number of beautiful subarrays
     */
    int beautifulSubarrays(vector<int> &nums, int numOdds) {
        int n = nums.size();
        if (n < numOdds) return 0;
        int count[n] = {0};
        count[0] = 1;
        int odd = 0, res = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] & 0x1) odd++;
            count[odd]++;
            if (odd >= numOdds) {
                res += count[odd - numOdds];
            }
        }
        return res;
    }
};

解法2:滑动窗口。但这题好像每次左右指针都要用while()移动,一般的模板不好用。试了好久。下次再做。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值