难度中等437收藏分享切换为英文接收动态反馈
给你一个整数数组 nums
和一个整数 k
,请你返回子数组内所有元素的乘积严格小于 k
的连续子数组的数目。
示例 1:
输入:nums = [10,5,2,6], k = 100 输出:8 解释:8 个乘积小于 100 的子数组分别为:[10]、[5]、[2],、[6]、[10,5]、[5,2]、[2,6]、[5,2,6]。 需要注意的是 [10,5,2] 并不是乘积小于 100 的子数组。
示例 2:
输入:nums = [1,2,3], k = 0 输出:0
提示:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
通过次数47,495提交次数104,394
解题思路
双指针,左右指针,不停的右乘,如果右乘发现大于K了,则左除,此为左除右乘法,期间不停的维护数量cnt
Python代码:
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
ans , cnt , i = 1 , 0 , 0
for j in range(len(nums)):
ans*=nums[j]
while ans>=k and i<=j:
ans//=nums[i]
i += 1
cnt += j-i+1
return cnt
C++代码:
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int cnt = 0 , ans = 1 , i = 0;
for (int j=0; j<nums.size(); j++){
ans *= nums[j];
while (i<=j && ans>=k){
ans /= nums[i];
i++;
}
cnt += j-i+1;
}
return cnt;
}
};