给定一个正整数数组 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的子数组。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ZVAVXX
class Solution(object):
def numSubarrayProductLessThanK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
lens = len(nums)
num = 1
result = 0
left, right = 0, 0
while right < lens:
num *= nums[right]
while left<=right and num>=k:
num /= nums[left]
left += 1
if left <= right:
result += right - left + 1
right += 1
return result