给定一个正整数数组 nums
和整数 k
,请找出该数组内乘积小于 k
的连续的子数组的个数。
示例 1:
输入: nums = [10,5,2,6], k = 100 输出: 8 解释: 8 个乘积小于 100 的子数组分别为: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]。 需要注意的是 [10,5,2] 并不是乘积小于100的子数组。
示例 2:
输入: nums = [1,2,3], k = 0 输出: 0
提示:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
注意:本题与主站 713 题相同:https://leetcode.cn/problems/subarray-product-less-than-k/
利用滑动窗口,我们能求出每个不同 right
结尾的合法子数组的个数
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
n = len(nums)
ans = 0
sum = 1
left, right = 0, 0
while right < n:
sum *= nums[right]
right += 1
while sum >= k and left < right:
sum /= nums[left]
left += 1
ans += right - left
return ans
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int n = nums.length;
int ans = 0;
int sum = 1;
int left = 0, right = 0;
while (right < n) {
sum *= nums[right++];
while (sum >= k && left < right) {
sum /= nums[left++];
}
ans += right - left;
}
return ans;
}
}
func numSubarrayProductLessThanK(nums []int, k int) int {
n := len(nums)
ans := 0
sum := 1
left, right := 0, 0
for right < n {
sum *= nums[right]
right++
for sum >= k && left < right {
sum /= nums[left]
left++
}
ans += right - left
}
return ans
}
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int left = 0, right;
long mul = 1;
int count = 0;
for (right = 0; right < nums.size(); right++) {
mul *= nums[right];
while (left <= right && mul >= k) {
mul /= nums[left++];
}
count += right >= left ? right - left + 1 : 0;
}
return count;
}
};