LeetCode.713 Subarray Product Less Than K(连续子数组乘积比k小的个数)

1.题目

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

2.说明

        给定数组nums和对应的k,输出满足连续子数组乘积小于k的个数。

3.解答

class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
        // 思路:1.如果用全排列求的方式,递归调用非常容易超时(而且需要分别记录加入集合的数和下标index),建议采用滑动窗口的思路。2.滑动窗口,分别采用头指针和尾指针,和当前范围内的和来记录。只要当前preProduct乘积不满足小于k,则头尾指针继续往右滑动。
        if (nums == null || nums.length == 0 || k <=1) {
            return 0;
        }
        int totalCount = 0;
        int head=0;
        int preProduct=1;
        for (int tail = 0; tail < nums.length; tail++) {
            preProduct *= nums[tail];
            while(preProduct>=k){
                // 确保每次都是从一个新的head头节点开始排列
                preProduct /= nums[head];
                head++;
            }

            // 每次从head到tail的组合个数为一个典型的阶梯:
            // 例如:1,2,3=>当head的下标为0 tail的下标为0时,只有[1]满足
            // 例如:1,2,3=>当head的下标为0 tail的下标为1时,只有[1,2],[2]满足
            // 例如:1,2,3=>当head的下标为0 tail的下标为2时,只有[1,2,3],[2,3],[3]满足
            // 综上所述:head到tail之间的个数统计为:tail-head+1
            
            totalCount += (tail - head + 1);
        }
        return totalCount;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值