题目:
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:
-
0 < nums.length <= 50000
. -
0 < nums[i] < 1000
. -
0 <= k < 10^6
.思路:
Two pointers问题:我们每次增加一个nums[end],然后从start开始,一旦发现[start, end]区间内的乘积大于k,就增加start。当[start, end]区间内的乘积小于k的时候,就会有(end - start + 1)个子区间符合条件。最后返回总的个数即可。算法的时间复杂度是O(n),空间复杂度是O(1)。
代码:
class Solution { public: int numSubarrayProductLessThanK(vector<int>& nums, int k) { int count = 0, start = 0, product = 1; for (int end = 0; end < nums.size(); ++end) { product *= nums[end]; while (start <= end && product >= k) { product /= nums[start]; ++start; } count += (end - start + 1); } return count; } };