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

188

被折叠的 条评论
为什么被折叠?



