Question
713. 乘积小于 K 的子数组
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subarray-product-less-than-k/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Ideas
1、Answer( Java )
解法思路:滑动窗口
👍当前元素合法的子数组数目 = 滑动窗口中元素的个数
Code
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int res = 0;
int curValue = 1;
int start = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= k) {
start = i + 1;
curValue = 1;
} else {
curValue *= nums[i];
while (curValue >= k) {
curValue /= nums[start];
start++;
}
}
if (curValue < k) {
res += i - start + 1;
}
}
return res;
}
}
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int res = 0, curValue = 1;
if (k <= 1) {
return 0;
}
for (int i = 0, j = 0; i < nums.length; i++) {
curValue *= nums[i];
while (curValue >= k) {
curValue /= nums[j++];
}
res += i - j + 1;
}
return res;
}
}
https://leetcode-cn.com/problems/subarray-product-less-than-k/solution/by-ac_oier-3w08/
|