[Leetcode] 713. Subarray Product Less Than K 解题报告

本文介绍了一种使用双指针技巧高效求解特定条件子数组数量的方法。针对给定的正整数数组,统计所有连续子数组中元素乘积小于k的数量。通过不断移动左右指针,实现O(n)时间复杂度和O(1)空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Your are given an array of positive integers nums.

Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is 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.

Note:

  • 0 < nums.length <= 50000.
  • 0 < nums[i] < 1000.
  • 0 <= k < 10^6.

    思路

    Two pointers问题:我们每次增加一个nums[end],然后从start开始,一旦发现[start, end]区间内的乘积大于k,就增加start。当[start, end]区间内的乘积小于k的时候,就会有(end - start + 1)个子区间符合条件。最后返回总的个数即可。算法的时间复杂度是O(n),空间复杂度是O(1)。

    代码

    class Solution {
    public:
        int numSubarrayProductLessThanK(vector<int>& nums, int k) {
            int count = 0, start = 0, product = 1;
            for (int end = 0; end < nums.size(); ++end) {
                product *= nums[end];
                while (start <= end && product >= k) {
                    product /= nums[start];
                    ++start;
                }
                count += (end - start + 1);
            }
            return count;
        }
    };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值