码迷,mamicode.com
首页 > 其他好文 > 详细

713. Subarray Product Less Than K

时间:2020-04-24 18:39:13      阅读:43      评论:0      收藏:0      [点我收藏+]

标签:input   highlight   while   ati   +=   note   res   tput   连续子数组   

问题:

求给定数组的连续子数组个数,使得子数组之乘积,小于给定值 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 };

 

713. Subarray Product Less Than K

标签:input   highlight   while   ati   +=   note   res   tput   连续子数组   

原文地址:https://www.cnblogs.com/habibah-chang/p/12769308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!