美文网首页
leetcode--713--乘积小于K的子数组

leetcode--713--乘积小于K的子数组

作者: minningl | 来源:发表于2020-12-09 00:19 被阅读0次

题目:
给定一个正整数数组 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

链接:https://leetcode-cn.com/problems/subarray-product-less-than-k

思路:
1、定义左右双指针,右指针先往右走,计算元素的乘积,如果乘积大于等于k则左指针往右走。其中右指针每往右走一步,只要乘积小于k,则计算一次当前的子数组数 right-left+1

Python代码:

class Solution(object):
    def numSubarrayProductLessThanK(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k<=1:
            return 0
        left, right = 0, 0
        product = 1
        ret = 0

        while right<len(nums):
            product *= nums[right]
            while product>=k:
                product /= nums[left]
                left += 1
            ret += (right-left+1)
            right += 1
        return ret

C++代码:

class Solution {
public:
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
        if(k<=1){
            return 0;
        }
        int left=0;
        int right=0;
        int product=1;
        int ret=0;

        while (right<nums.size()){
            product *= nums[right];
            while(product>=k){
                product /= nums[left];
                left += 1;
            }
            ret += (right-left+1);
            right += 1;
        }
        return ret;
    }
};
``

相关文章

网友评论

      本文标题:leetcode--713--乘积小于K的子数组

      本文链接:https://www.haomeiwen.com/subject/anscgktx.html