LeetCode刷题笔记15
713. 乘积小于K的子数组
题目描述
给定一个正整数数组 nums。
找出该数组内乘积小于 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的子数组。
说明:
0 < nums.length <= 50000
0 < nums[i] < 1000
0 <= k < 10^6
思路
滑动窗口问题
代码
python
class Solution(object):
def numSubarrayProductLessThanK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k<=1: return 0
left=0
right=0
res=1
count=0
while(right<len(nums)):
res*=nums[right]
while(res>=k):
res/=nums[left]
left+=1
count+=right-left+1
right+=1
return count
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if (k<=1) return 0;
int left=0,right=0,count=0,res=1;
while(right<nums.size()){
res*=nums[right];
while(res>=k){
res/=nums[left];
left+=1;
}
count+=right-left+1;
right+=1;
}
return count;
}
};
java
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
if (k<=1) return 0;
int left=0,right=0,count=0,res=1;
while(right<nums.length){
res*=nums[right];
while(res>=k){
res/=nums[left];
left+=1;
}
count+=right-left+1;
right+=1;
}
return count;
}
}