• 713. Subarray Product Less Than K


    问题:

    求给定数组的连续子数组个数,使得子数组之乘积,小于给定值 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 };
  • 相关阅读:
    redux
    ajax跨域例子
    flux
    BSON数据格式
    JS代码风格自动规整工具Prettier
    JS通用模块模式 UMD
    Promise库
    webpack打包理解
    前端自动提示功能插件-typeahead
    socket.io emit callback调用探秘
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12769308.html
Copyright © 2020-2023  润新知