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个数. 

Note: Corner case. k <= 1, return 0. e.g. [1, 1, 1] and k = 1.

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.

posted @ 2017-10-31 14:46  Dylan_Java_NYC  阅读(500)  评论(0编辑  收藏  举报