码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Subarray Product Less Than K

时间:2017-10-31 14:58:13      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:++   计数   链接   esc   r++   等于   表示   class   msu   

原题链接在这里: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.

LeetCode Subarray Product Less Than K

标签:++   计数   链接   esc   r++   等于   表示   class   msu   

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/7761472.html

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