本文已参与「新人创作礼」活动,一起开启掘金创作之路。
原文链接:blog.csdn.net/roufoo/arti…
Subarray Product Less Than K 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 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. 1 2 3 Example 2: Input: nums = [5,10,2], k = 10 Output: 2
Explanation: Only [5] and [2]. 1 2 Notice 0 < nums.length <= 50000. 0 < nums[i] < 1000. 0 <= k < 10^6.
这题因为有空间限制,不能用预处理记下i,j之间的乘积,也不能用DP,因为会用到二维数组。
解法1: 我的解法是每次从i往左动,若product>k退出,否则count++。 这个算法会有冗余计算。但总的复杂度还是O(n^2)。
class Solution {
public:
/**
* @param nums: an array
* @param k: an integer
* @return: the number of subarrays where the product of all the elements in the subarray is less than k
*/
int numSubarrayProductLessThanK(vector<int> &nums, int k) {
int n = nums.size();
if (n == 0) return 0;
long long product = 1;
for (int i = 0; i < n; ++i) {
helper(nums, i, k);
}
return count;
}
private:
int count = 0;
void helper(vector<int> & nums, int index, int k) {
long long product = 1;
for (int i = index; i >= 0; i--) {
if (nums[i] > k) break;
product *= nums[i];
if (product < k) {
count++;
} else {
break;
}
}
}
};
解法2: 网上看到一个很牛的解法。 www.cnblogs.com/grandyang/p…
class Solution {
public:
/**
* @param nums: an array
* @param k: an integer
* @return: the number of subarrays where the product of all the elements in the subarray is less than k
*/
int numSubarrayProductLessThanK(vector<int> &nums, int k) {
int n = nums.size();
if (n == 0|| k == 0) return 0;
long long product = 1;
int count = 0;
int left = 0, right = 0;
while (right < n) {
product *= nums[right];
while (product >= k) {
product /= nums[left];
left++;
}
count += right - left + 1;
right++;
}
return count;
}
};