码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode 713 Subarray Product Less Than K (子数组乘积大于K的个数) (双指针)

时间:2020-03-29 11:09:56      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:return   0ms   目录   osi   product   tco   class   bar   nts   

Leetcode 713

问题描述

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.

方法

** Solution Java **
** 7ms, beats 98.53% **
** 49.5MB, beats 100.00% **
class Solution {
    public int numSubarrayProductLessThanK(int[] nums, int k) {
        if (k == 0)
            return 0;
        int product = 1, res = 0, n = nums.length;
        for (int left = 0, right = 0; right < n; ++right){
            product *= nums[right];
            while (left <= right && product >= k) 
                product /= nums[left++];
            res += right - left + 1;
        }
        return res;
    }
}
** Solution Python3 **
** 1060ms, beats 36.99% **
** 16.7MB, beats 14.29% **
class Solution(object):
    def numSubarrayProductLessThanK(self, nums, k):
        if (k == 0) :
            return 0
        product, res, left = 1, 0, 0
        for right in range(len(nums)) :
            product *= nums[right]
            while (left <= right and k <= product) :
                product /= nums[left]
                left += 1
            res += right - left + 1
        return res

Leetcode 713 Subarray Product Less Than K (子数组乘积大于K的个数) (双指针)

标签:return   0ms   目录   osi   product   tco   class   bar   nts   

原文地址:https://www.cnblogs.com/willwuss/p/12590981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!