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.

  • 相关阅读:
    关于java和jvm的思考
    java之try、catch、finally
    Microsoft SQLServer有四种系统数据库
    HDU 5087
    uva639 暴力、回溯
    uva127
    uva 131
    洛谷 P2580 于是他错误的点名开始了
    字典树(trie)
    HTML学习笔记
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7761472.html
Copyright © 2011-2022 走看看