LeetCode 713. Subarray Product Less Than K

本文介绍了一种使用双指针法解决数组中连续子数组乘积小于特定值K的问题。通过调整两个指针的位置,算法可以高效地遍历整个数组并计算满足条件的子数组数量。

Problem Description:

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.

题解:

很快想到了two pointer的解法,但是一直被corner case困住。

两个典型的case

[1,2,3]

0

这个情况是可能导致j < i,所以要加上j= Math.max(i, j)

还有

[1,1,1,8,1,1,1,1,1,1,1,1,1]

5

除以8可能导致prod = 0,仅仅当i < j的时候才能做除法

class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
        int prod = 1;
        int res = 0;
        for(int i = 0, j = 0; i < nums.length; i++) {
            j = Math.max(i, j);
            while(j < nums.length && prod * nums[j] < k) {
                prod *= nums[j++];
            }
            res += j - i;
            if(i < j) prod /= nums[i];
        }
        return res;
    }
}

 

转载于:https://www.cnblogs.com/rookielet/p/10620886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值