【LeetCode】713. Subarray Product Less Than K

本文介绍了一个算法问题,即计算一个正整数数组中所有连续子数组的数量,这些子数组的元素乘积小于给定阈值k。通过使用两指针技术和滑动窗口的概念,文章详细解释了如何有效地解决这个问题,并提供了一个C++实现的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Your are given an array of positive integers nums.

Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than 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.

思路:打印出所有积小于k的子数组个数,两指针,简单的滑动窗口,维持窗口内乘积小于k否则i++,每次都是j++,这里更新ans有技巧,每次都加上窗口长度实际上就是新节点到原来窗口里的每个数之间形成的子数组;也可以通过len,对于每个i,第一个for是以i为中心,递增len,第二个是偶数,len通过回文两遍拓展

class Solution {
public:
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
       if(k<=1) return 0;
        int i=0,cnt=0,res=1;
        
        for(int j=0;j<nums.size();j++){
            res*=nums[j];
            while(res>=k) res/=nums[i++];
            cnt+=j-i+1;
        }
        return cnt;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值