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()移动,一般的模板不好用。试了好久。下次再做。
文章描述了一个编程问题,要求在给定整数数组中找到具有指定奇数元素的美丽子数组,即子数组中奇数元素数量等于给定值。提供了两种解法:一种是使用累积计数,另一种是尝试滑动窗口方法但未完全实现。
244

被折叠的 条评论
为什么被折叠?



