Leetcode-713. 乘积小于 K 的子数组
Problem: 713. 乘积小于 K 的子数组
思路
滑动窗口
解题过程
维护一个窗口[l,r],代表以r为右端点的满足元素乘积小于k的最长子数组。此时数组长度就是以r为右端点的满足条件的子数组个数。
mul记录窗口内容所有元素的乘积。当窗口右移的时候,更新乘积。如果乘积大于等于k,需要左移窗口来缩小乘积。
Code
c++
class Solution {
public:int numSubarrayProductLessThanK(vector<int>& nums, int k) {int n = nums.size();int l = 0;int ans = 0;long long mul = 1;for (int r = 0; r < n; r++) {mul *= nums[r];while (mul >= k && l <= r) {mul /= nums[l];l++;}ans += r - l + 1;}return ans;}
};
python
class Solution:def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:n = len(nums)l = ans = 0mul = 1for r, x in enumerate(nums):mul *= xwhile mul >= k and l <= r:mul /= nums[l]l += 1ans += r - l + 1return ans
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(1)