zoukankan      html  css  js  c++  java
  • LeetCode 713. Subarray Product Less Than K

    原题链接在这里:https://leetcode.com/problems/subarray-product-less-than-k/description/

    题目:

    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.

    题解:

    都是正数, 所以乘积prod是递增的.

    使用sliding window, sliding window prod小于k时右侧前进, 大于等于k时左侧前进.

    维护计数. 右侧减左侧加一 表示以当前右侧为尾的subarray个数. 

    Time Complexity: O(nums.length).

    Space: O(1).

    AC Java:

     1 class Solution {
     2     public int numSubarrayProductLessThanK(int[] nums, int k) {
     3         if(nums == null || nums.length == 0 || k <= 1){
     4             return 0;
     5         }
     6         
     7         int res = 0;
     8         int prod = 1;
     9         int l = 0;
    10         int r = 0;
    11         while(r < nums.length){
    12             prod *= nums[r];
    13             while(prod >= k){
    14                 prod /= nums[l++];
    15             }
    16             res += r-l+1;
    17             r++;
    18         }
    19         
    20         return res;
    21     }
    22 }

    类似Subarray Sum Equals K.

  • 相关阅读:
    图片处理
    define 常量的定义和读取
    curl
    stream_get_contents 和file_get_content的区别
    php flock 文件锁
    字符串函数
    php 常量
    debug_backtrace()
    pathlib模块替代os.path
    Python中对 文件 的各种骚操作
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7761472.html
Copyright © 2011-2022 走看看