其他分享
首页 > 其他分享> > LeetCode 713 Subarray Product Less Than K 滑动窗口

LeetCode 713 Subarray Product Less Than K 滑动窗口

作者:互联网

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.

Solution

滑动窗口的思想。不断增大右端点 \(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;
    }
};

标签:Product,端点,nums,int,Less,713,Solution,pd,滑动
来源: https://www.cnblogs.com/xinyu04/p/16541287.html