713. Subarray Product Less Than K

这篇博客介绍了如何使用滑动窗口算法解决数组中子数组乘积小于特定值K的问题。通过左右指针动态调整窗口大小,确保窗口内元素乘积始终小于K,从而统计符合条件的子数组数量。文章提供了详细的思路解析和代码实现,适用于理解和应用滑动窗口算法。
摘要由CSDN通过智能技术生成

题目:

Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.

Example 1:

Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Example 2:

Input: nums = [1,2,3], k = 0
Output: 0

Constraints:

  • 1 <= nums.length <= 3 * 104
  • 1 <= nums[i] <= 1000
  • 0 <= k <= 106

思路:

左右指针滑动窗口,初始化左右指针都是0,之后右指针一路右移,那么每一次右移,只要积小于k,那么路径上的都符合结果,即一共有right - left + 1种:假设窗口为[left, right],且nums[left] * nums[left + 1] * ...... * nums[right - 1] * nums[right]的积小于k,那么nums[left], nums[left] * nums[left + 1],........, nums[left] * nums[left + 1] *...... nums[right - 1] * nums[right]都是合规的答案,总共就是right - left + 1种。 当积大于等于k的时候,则需要左指针往右移,同时当前积要除以nums[l]。

代码:

class Solution {
public:
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
        if (k <= 1) return 0;
        int cur = 1;
        int l = 0, r = 0;
        int ans = 0;
        while (r < nums.size()) {
            cur *= nums[r];
            while (cur >= k) {
                cur /= nums[l];
                l++;
            }
            
            ans += r - l + 1;
            r++;
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值