1.题目
Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Example 2:
Input: nums = [1,2,3], k = 0
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
2.说明
给定数组nums和对应的k,输出满足连续子数组乘积小于k的个数。
3.解答
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
// 思路:1.如果用全排列求的方式,递归调用非常容易超时(而且需要分别记录加入集合的数和下标index),建议采用滑动窗口的思路。2.滑动窗口,分别采用头指针和尾指针,和当前范围内的和来记录。只要当前preProduct乘积不满足小于k,则头尾指针继续往右滑动。
if (nums == null || nums.length == 0 || k <=1) {
return 0;
}
int totalCount = 0;
int head=0;
int preProduct=1;
for (int tail = 0; tail < nums.length; tail++) {
preProduct *= nums[tail];
while(preProduct>=k){
// 确保每次都是从一个新的head头节点开始排列
preProduct /= nums[head];
head++;
}
// 每次从head到tail的组合个数为一个典型的阶梯:
// 例如:1,2,3=>当head的下标为0 tail的下标为0时,只有[1]满足
// 例如:1,2,3=>当head的下标为0 tail的下标为1时,只有[1,2],[2]满足
// 例如:1,2,3=>当head的下标为0 tail的下标为2时,只有[1,2,3],[2,3],[3]满足
// 综上所述:head到tail之间的个数统计为:tail-head+1
totalCount += (tail - head + 1);
}
return totalCount;
}
}