Description
Your are given an array of positive integers nums.
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
Example 1
Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Note
1. 0 < nums.length <= 50000.
2. 0 < nums[i] < 1000.
3. 0 <= k < 10^6.
Solution 1(C++)
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if (k <= 1) return 0;
int n = nums.size(), prod = 1, ans = 0, left = 0;
for (int i = 0; i < n; i++) {
prod *= nums[i];
while (prod >= k) prod /= nums[left++];
ans += i - left + 1;
}
return ans;
}
};
后续更新
2018-5-12与之类似的题目可参考:
算法分析
这一道题,我其实最应该注意的关键词是:the number of (contiguous) subarrays。这两个词一出来,就可以应该有思路:参考:
LeetCode-560. Subarray Sum Equals K;
LeetCode-795. Number of Subarrays with Bounded Maximum;
所以这也是基本题型的变种。我就不罗嗦了,基本想法与上面两道题是类似的。
程序分析
略。
本文探讨了一道算法题目,即统计一个正整数数组中所有连续子数组的数量,这些子数组的所有元素乘积小于给定值k。通过示例说明了如何筛选符合条件的子数组,并给出了解决方案。

494

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



