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()移动,一般的模板不好用。试了好久。下次再做。

你可能感兴趣的:(算法,数据结构)