leetcode713. 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

思路:使用滑动窗口的思路,找取每一个符合条件的小窗,统计其内部子数组数量。

注意,对于某一个值,我们只关注以它为最右边元素的子数组。这样可以减少重复讨论的麻烦。

python 复制代码
class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        if k <= 1: return 0
        left, right, multi, ans = 0, 0, 1, 0
        while right < len(nums):
            multi *= nums[right] # 以右侧元素为pivot
            while multi >= k: # 找到对应这个pivot的最长窗口左侧点
                multi //= nums[left]
                left += 1
            ans += right - left + 1 # 统计以pivot为右侧元素的子数组
            right += 1
        return ans
相关推荐
今天背单词了吗9805 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
jdlxx_dongfangxing6 小时前
进制转换算法详解及应用
算法
why技术7 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法
2501_922895588 小时前
字符函数和字符串函数(下)- 暴力匹配算法
算法
IT信息技术学习圈8 小时前
算法核心知识复习:排序算法对比 + 递归与递推深度解析(根据GESP四级题目总结)
算法·排序算法
愚润求学9 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
会唱歌的小黄李9 小时前
【算法】贪心算法入门
算法·贪心算法
轻语呢喃10 小时前
每日LeetCode : 两数相加--链表操作与进位的经典处理
javascript·算法
钢铁男儿10 小时前
C# 接口(接口可以继承接口)
java·算法·c#
zl_vslam11 小时前
SLAM中的非线性优化-2D图优化之激光SLAM cartographer前端匹配(十七)
前端·人工智能·算法