[LeetCode] 713. Subarray Product Less Than K

Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly 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.

Example 2:

Input: nums = [1,2,3], k = 0
Output: 0

Constraints:

  • 1 <= nums.length <= 3 * 104
  • 1 <= nums[i] <= 1000
  • 0 <= k <= 106

乘积小于 K 的子数组。

给你一个整数数组 nums 和一个整数 k ,请你返回子数组内所有元素的乘积严格小于 k 的连续子数组的数目。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/subarray-product-less-than-k
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题也是比较经典的滑动窗口的题,可以直接套用76题的模板。注意子数组的计算方法。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int numSubarrayProductLessThanK(int[] nums, int k) {
 3         int count = 0;
 4         int product = 1;
 5         int start = 0;
 6         int end = 0;
 7         while (end < nums.length) {
 8             product *= nums[end];
 9             end++;
10             while (start < end && product >= k) {
11                 product /= nums[start];
12                 start++;
13             }
14             count += end - start;
15         }
16         return count;
17     }
18 }

 

sliding window相关题目

LeetCode 题目总结

posted @ 2020-06-10 08:02  CNoodle  阅读(210)  评论(0编辑  收藏  举报