LeetCode 题解工作台

乘积小于 K 的子数组

给你一个整数数组 nums 和一个整数 k ,请你返回子数组内所有元素的乘积严格小于 k 的连续子数组的数目。 示例 1: 输入: nums = [10,5,2,6], k = 100 输出: 8 解释: 8 个乘积小于 100 的子数组分别为:[10]、[5]、[2]、[6]、[10,5]、[5,…

category

4

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·搜索·答案·空间

bolt

答案摘要

我们可以用双指针维护一个滑动窗口,窗口内所有元素的乘积小于 。 定义两个指针 和 分别指向滑动窗口的左右边界,初始时 $l = r = 0$。我们用一个变量 记录窗口内所有元素的乘积,初始时 $p = 1$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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
lightbulb

解题思路

方法一:双指针

我们可以用双指针维护一个滑动窗口,窗口内所有元素的乘积小于 kk

定义两个指针 llrr 分别指向滑动窗口的左右边界,初始时 l=r=0l = r = 0。我们用一个变量 pp 记录窗口内所有元素的乘积,初始时 p=1p = 1

每次,我们将 rr 右移一位,将 rr 指向的元素 xx 加入窗口,更新 p=p×xp = p \times x。然后,如果 pkp \geq k,我们循环地将 ll 右移一位,并更新 p=p÷nums[l]p = p \div \text{nums}[l],直到 p<kp < k 或者 l>rl \gt r 为止。这样,以 rr 结尾的、乘积小于 kk 的连续子数组的个数即为 rl+1r - l + 1。然后我们将答案加上这个数量,并继续移动 rr,直到 rr 到达数组的末尾。

时间复杂度 O(n)O(n),其中 nn 为数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
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
speed

复杂度分析

指标
时间O(n \cdot \log(n))
空间O(n)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

乘积小于 K 的子数组题解:二分·搜索·答案·空间 | LeetCode #713 中等