LeetCode刷题15-- 乘积小于K的子数组

713. 乘积小于K的子数组

链接

题目描述

给定一个正整数数组 nums。

找出该数组内乘积小于 k 的连续的子数组的个数。

示例 1:

输入: nums = [10,5,2,6], k = 100
输出: 8
解释: 8个乘积小于100的子数组分别为: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]。
需要注意的是 [10,5,2] 并不是乘积小于100的子数组。

说明:

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

思路

滑动窗口问题

代码

python

class Solution(object):
    def numSubarrayProductLessThanK(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k<=1: return 0
        left=0
        right=0
        res=1
        count=0
        while(right<len(nums)):
            res*=nums[right]
            while(res>=k):
                res/=nums[left]
                left+=1
            count+=right-left+1
            right+=1
        return count
class Solution {
public:
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
        if (k<=1) return 0;
        int left=0,right=0,count=0,res=1;
        while(right<nums.size()){
            res*=nums[right];
            while(res>=k){
                res/=nums[left];
                left+=1;
            }
            count+=right-left+1;
            right+=1;
        }
        return count;

    }
};

java

class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
        if (k<=1) return 0;
        int left=0,right=0,count=0,res=1;
        while(right<nums.length){
            res*=nums[right];
            while(res>=k){
                res/=nums[left];
                left+=1;
            }
            count+=right-left+1;
            right+=1;
        }
        return count;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值