class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
}
};
剑指 Offer II 009. 乘积小于 K 的子数组
给定一个正整数数组 nums
和整数 k
,请找出该数组内乘积小于 k
的连续的子数组的个数。
示例 1:
输入: nums = [10,5,2,6], k = 100 输出: 8 解释: 8 个乘积小于 100 的子数组分别为: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]。 需要注意的是 [10,5,2] 并不是乘积小于100的子数组。
示例 2:
输入: nums = [1,2,3], k = 0 输出: 0
提示:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
注意:本题与主站 713 题相同:https://leetcode.cn/problems/subarray-product-less-than-k/
原站题解
python3 解法, 执行用时: 256 ms, 内存消耗: 17.6 MB, 提交时间: 2022-11-23 11:17:28
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: if k == 0: return 0 ans, n = 0, len(nums) logPrefix = [0] * (n + 1) for i, num in enumerate(nums): logPrefix[i + 1] = logPrefix[i] + log(num) logK = log(k) for j in range(1, n + 1): l = bisect_right(logPrefix, logPrefix[j] - logK + 1e-10, 0, j) ans += j - l return ans
golang 解法, 执行用时: 88 ms, 内存消耗: 7 MB, 提交时间: 2022-11-23 11:15:14
func numSubarrayProductLessThanK(nums []int, k int) (ans int) { if k == 0 { return } n := len(nums) logPrefix := make([]float64, n+1) for i, num := range nums { logPrefix[i+1] = logPrefix[i] + math.Log(float64(num)) } logK := math.Log(float64(k)) for j := 1; j <= n; j++ { l := sort.SearchFloat64s(logPrefix[:j], logPrefix[j]-logK+1e-10) ans += j - l } return }
golang 解法, 执行用时: 64 ms, 内存消耗: 7.2 MB, 提交时间: 2022-11-23 11:14:52
func numSubarrayProductLessThanK(nums []int, k int) (ans int) { prod, i := 1, 0 for j, num := range nums { prod *= num for ; i <= j && prod >= k; i++ { prod /= nums[i] } ans += j - i + 1 } return }
python3 解法, 执行用时: 192 ms, 内存消耗: 17.1 MB, 提交时间: 2022-11-23 11:13:44
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: ans, prod, i = 0, 1, 0 for j, num in enumerate(nums): prod *= num while i <= j and prod >= k: prod //= nums[i] i += 1 ans += j - i + 1 return ans