LeetCode 题解工作台
乘积小于 K 的子数组
给你一个整数数组 nums 和一个整数 k ,请你返回子数组内所有元素的乘积严格小于 k 的连续子数组的数目。 示例 1: 输入: nums = [10,5,2,6], k = 100 输出: 8 解释: 8 个乘积小于 100 的子数组分别为:[10]、[5]、[2]、[6]、[10,5]、[5,…
4
题型
9
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们可以用双指针维护一个滑动窗口,窗口内所有元素的乘积小于 。 定义两个指针 和 分别指向滑动窗口的左右边界,初始时 $l = r = 0$。我们用一个变量 记录窗口内所有元素的乘积,初始时 $p = 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
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 * 1041 <= nums[i] <= 10000 <= k <= 106
解题思路
方法一:双指针
我们可以用双指针维护一个滑动窗口,窗口内所有元素的乘积小于 。
定义两个指针 和 分别指向滑动窗口的左右边界,初始时 。我们用一个变量 记录窗口内所有元素的乘积,初始时 。
每次,我们将 右移一位,将 指向的元素 加入窗口,更新 。然后,如果 ,我们循环地将 右移一位,并更新 ,直到 或者 为止。这样,以 结尾的、乘积小于 的连续子数组的个数即为 。然后我们将答案加上这个数量,并继续移动 ,直到 到达数组的末尾。
时间复杂度 ,其中 为数组的长度。空间复杂度 。
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
ans = l = 0
p = 1
for r, x in enumerate(nums):
p *= x
while l <= r and p >= k:
p //= nums[l]
l += 1
ans += r - l + 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \cdot \log(n)) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Understand how binary search over the valid space works with respect to subarrays.
- question_mark
Candidate uses efficient sliding window or binary search techniques instead of brute-force methods.
- question_mark
Look for ability to balance correctness with time complexity optimizations.
常见陷阱
外企场景- error
Failing to adjust the window size properly when the product exceeds k.
- error
Using a brute-force approach that evaluates all possible subarrays instead of leveraging efficient algorithms.
- error
Misunderstanding the sliding window or binary search approach, resulting in suboptimal performance.
进阶变体
外企场景- arrow_right_alt
Change the constraint for k to be very large, testing how the solution scales with larger values of k.
- arrow_right_alt
Vary the array length significantly to assess performance under different input sizes.
- arrow_right_alt
Introduce negative numbers in the array and adjust the problem to handle those.