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
.
滑动窗口的思想。不断增大右端点 \(r\), 当乘积 \(pd\ge k\) 的时候,缩小左端点 \(l\),最后得到的区间里面所有的子区间都满足条件: 数量为 \(r-l+1\)
class Solution { private: int ans = 0; public: int numSubarrayProductLessThanK(vector<int>& nums, int k) { int pd = 1; int n = nums.size(); if(k<=1) return 0; int l = 0; for(int r = 0;r<n;r++){ pd*=nums[r]; while(pd>=k && l<=r){ pd/=nums[l];l++; } //l--; ans+=(r-l+1); } return ans; } };