Leetcode-713. 乘积小于 K 的子数组

Problem: 713. 乘积小于 K 的子数组

思路

滑动窗口

解题过程

维护一个窗口[l,r],代表以r为右端点的满足元素乘积小于k的最长子数组。此时数组长度就是以r为右端点的满足条件的子数组个数。

mul记录窗口内容所有元素的乘积。当窗口右移的时候,更新乘积。如果乘积大于等于k,需要左移窗口来缩小乘积。

Code

c++

class Solution {
public:
    int numSubarrayProductLessThanK(vector& 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 = 0
        mul = 1

        for r, x in enumerate(nums):
            mul *= x
            while mul >= k and l <= r:
                mul /= nums[l]
                l += 1
            ans += r - l + 1

        return ans

复杂度

  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

    你可能感兴趣的:(Leetcode,#滑动窗口,算法,数据结构)