lc713-乘积小于K的子数组

lc713-乘积小于K的子数组

题目

给定一个正整数数组 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

注意:本题与主站 713 题相同:https://leetcode-cn.com/problems/subarray-product-less-than-k/

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ZVAVXX
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Code

MyCode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//my_Code 滑动窗口 注意 cnt的运算逻辑
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int len=nums.size();
int cnt=0;
int left=0,right=0;
int prod=nums[0];
while(right<len)
{
if(prod<k)
{
cnt+=right-left+1; //固定右边 向左看 本行为关键
right++;
if(right==len)break;
prod*=nums[right];
}
else
{
if(left==len)break;
prod/=nums[left];
left++;
}
}
return cnt;
}
};

Standard_Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//standard_code
class Solution(object):
def numSubarrayProductLessThanK(self, nums, k):
if k <= 1: return 0
prod = 1
ans = left = 0
for right, val in enumerate(nums):
prod *= val
while prod >= k:
prod /= nums[left]
left += 1
ans += right - left + 1
return ans

作者:LeetCode
链接:https://leetcode-cn.com/problems/subarray-product-less-than-k/solution/cheng-ji-xiao-yu-kde-zi-shu-zu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Solution&Key Points

对ABCX 固定X 则满足条件的有X CX BCX ABCX 四个 ,避免重复计算

查看评论