LeetCode 713. Subarray Product Less Than 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;
    }
}

 

posted @ 2019-03-29 14:05  起点菜鸟  阅读(139)  评论(0编辑  收藏  举报