zoukankan      html  css  js  c++  java
  • 0713. Subarray Product Less Than K (M)

    Subarray Product Less Than K (M)

    题目

    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.


    题意

    找到所有的连续子数组,使其积小于指定值。

    思路

    遍历数组所有元素作为区间右端点;对于每个右端点,找到最左侧的元素,使构成的区间的积小于指定值;累加以右端点为终点的子区间的数量。


    代码实现

    Java

    class Solution {
        public int numSubarrayProductLessThanK(int[] nums, int k) {
            int count = 0;
            int left = 0, product = 1;
            for (int right = 0; right < nums.length; right++) {
                product *= nums[right];
                while (product >= k && left <= right) {
                    product /= nums[left++];
                }
                count += right - left + 1;
            }
            return count;
        }
    }
    
  • 相关阅读:
    Linux查看系统信息
    pgrep 和 pkill 使用小记
    linux下json库的编译及例程
    Epoll 实例
    gcc中的内嵌汇编语言
    BZOJ 1053: [HAOI2007]反素数ant
    2018.7.15模拟赛
    BZOJ 2002: [Hnoi2010]Bounce 弹飞绵羊
    BZOJ 4241: 历史研究
    LUOGU P2365 任务安排
  • 原文地址:https://www.cnblogs.com/mapoos/p/13747371.html
Copyright © 2011-2022 走看看