问题:
求给定数组的连续子数组个数,使得子数组之乘积,小于给定值 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.
解法:
窗口法,
左窗口low,右窗口high
主要移动 high,每加一个满足条件的high,子数组数+=(high-low)+1
如果乘积大于 k,那么向右移动左窗口low,同时乘积/nums[low]
参考代码:
1 class Solution { 2 public: 3 int numSubarrayProductLessThanK(vector<int>& nums, int k) { 4 int res=0; 5 int low=0, high=0; 6 if(nums.size()==0||k==0)return res; 7 int protmp=1; 8 for(low=0,high=0;high<nums.size();high++){ 9 protmp*=nums[high]; 10 while(low<=high && protmp>=k){ 11 protmp/=nums[low]; 12 low++; 13 } 14 res+=(high-low+1); 15 } 16 return res; 17 } 18 };