1 """
2 Your are given an array of positive integers nums.
3 Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
4 Example 1:
5 Input: nums = [10, 5, 2, 6], k = 100
6 Output: 8
7 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
8 Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
9 """
10 """
11 正确做法,双指针加滑动窗口
12 很是巧妙
13 pro为乘积,pro不断乘以nums[j]得到子数组乘积,满足条件小于k时
14 !!!
15 res +=(j-i+1),res是计数器。
16 滑动窗口内元素间的相互组合的数量
17 """
18 class Solution1:
19 def numSubarrayProductLessThanK(self, nums, k):
20 res, i = 0, 0
21 pro = 1 #乘积
22 if k <= 1: # 对于案例nums=[1, 2, 3] k=0 和 nums=[1, 1, 1] k=1
23 return 0
24 for j in range(len(nums)):
25 pro = pro * nums[j]
26 while pro >= k:
27 pro = pro // nums[i]
28 i += 1
29 res += j - i + 1 #!!!这个很关键
30 return res
31
32 """
33 我的解法超时,
34 对于输入nums = [1, 1, 1, 1......,1] k=5
35 """
36 class Solution2:
37 def numSubarrayProductLessThanK(self, nums, k):
38 res = 0
39 for i in range(len(nums)):
40 pro = 1
41 j = i
42 while j < len(nums):
43 if nums[j] * pro < k:
44 res += 1
45 pro = nums[j] * pro
46 j += 1
47 else:
48 break
49 return res