题目:
Given an array of integers nums
and an integer k
, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly 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.
Example 2:
Input: nums = [1,2,3], k = 0 Output: 0
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
思路:
左右指针滑动窗口,初始化左右指针都是0,之后右指针一路右移,那么每一次右移,只要积小于k,那么路径上的都符合结果,即一共有right - left + 1种:假设窗口为[left, right],且nums[left] * nums[left + 1] * ...... * nums[right - 1] * nums[right]的积小于k,那么nums[left], nums[left] * nums[left + 1],........, nums[left] * nums[left + 1] *...... nums[right - 1] * nums[right]都是合规的答案,总共就是right - left + 1种。 当积大于等于k的时候,则需要左指针往右移,同时当前积要除以nums[l]。
代码:
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if (k <= 1) return 0;
int cur = 1;
int l = 0, r = 0;
int ans = 0;
while (r < nums.size()) {
cur *= nums[r];
while (cur >= k) {
cur /= nums[l];
l++;
}
ans += r - l + 1;
r++;
}
return ans;
}
};