乘积小于K的子数组
作者:互联网
https://leetcode-cn.com/problems/ZVAVXX/
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int left = 0, ans = 0;
int sum = 1;
//
for (int i = 0; i < nums.length; i ++) {
//当前子数组乘积
sum *= nums[i];
//如果乘积不小于k,那么在i左边,每次减少一个数组元素的乘积,来找出可能的子数组
while (left <= i && sum >= k) {
sum /= nums[left ++];
}
//此时的left<=i且[left, i]的乘积小于k
if (left <= i) {
ans += i - left + 1;
}
}
return ans;
}
}
标签:小于,乘积,nums,int,sum,数组,ans,left 来源: https://blog.csdn.net/qq_43806430/article/details/122413244