当前位置:网站首页>【leetcode】剑指 Offer II 009. 乘积小于 K 的子数组(滑动窗口、双指针)
【leetcode】剑指 Offer II 009. 乘积小于 K 的子数组(滑动窗口、双指针)
2022-08-03 19:24:00 【friedrichor】
剑指 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 < = n u m s . l e n g t h < = 3 ∗ 1 0 4 1 <= nums.length <= 3 * 10^4 1<=nums.length<=3∗104
- 1 < = n u m s [ i ] < = 1000 1 <= nums[i] <= 1000 1<=nums[i]<=1000
- 0 < = k < = 1 0 6 0 <= k <= 10^6 0<=k<=106
题解
这题和 【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针) 比较相似。
滑动窗口枚举
不出意外,这个又超时了
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
def multiply(num_list): # 累乘
res = 1
for num in num_list:
res *= num
return res
num = 0
for size in range(1, len(nums) + 1):
for i in range(len(nums) + 1 - size):
sum_window = multiply(nums[i: i + size])
if sum_window < k:
num += 1
return num
双指针
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
length = len(nums)
num = 0
left = 0
sum = 1
for right, value in enumerate(nums):
sum *= value
while sum >= k and left <= right:
sum /= nums[left]
left += 1
num += right - left + 1
return num
以 nums = [10,5,2,6], k = 100 为例:
right = 0
[10] 5 2 6 sum < k num += 0-0+1 = 1 [10]
right = 1
[10 5] 2 6 sum < k num += 1-0+1 = 2 [5] [10 5]
right = 2
[10 5 2] 6 sum = k
10 [5 2] 6 sum < k num += 2-1+1 = 2 [2] [5 2]
right = 3
10 [5 2 6] sum < k num += 3-1+1 = 3 [6] [2 6] [5 2 6]

边栏推荐
- X86函数调用模型分析
- 基于DMS的数仓智能运维服务,知多少?
- 阿里巴巴政委体系-第五章、阿里政委体系建设
- 红日安全内网渗透靶场-VulnStack-1
- Brush the topic of mobile zero power button
- 阿里巴巴政委体系-第九章、阿里政委启示录
- Postgresql source code (64) Query execution - data structure and execution process before submodule Executor (2) execution
- FreeRTOS中级篇
- 线上一次JVM FullGC搞得整晚都没睡,彻底崩溃
- OneNote 教程,如何在 OneNote 中设置页面格式?
猜你喜欢

阿里巴巴政委体系-第六章、阿里政委体系运作

红日安全内网渗透靶场-VulnStack-1

LeetCode 952. 按公因数计算最大组件大小

Don't look down upon the WebSocket!Long connection, stateful, two-way, full-duplex king is Fried

阿里巴巴政委体系-第五章、阿里政委体系建设

入门3D建模基础教程详细分解

MYSQL误删数据恢复

从文本匹配到语义相关——新闻相似度计算的一般思路

MySQL【变量、流程控制与游标】

LeetCode 952. Calculate Maximum Component Size by Common Factor
随机推荐
U-Net生物医学图像分割讲解(Convolutional Networks for BiomedicalImage Segmentation)
Solution for no navigation bar after Word is saved as PDF
SQL server 实现触发器备份表数据
分享即时通讯开发之WebSocket:概念、原理、易错常识、动手实践
七夕之前,终于整出了带AI的美丽秘笈
LOL英雄联盟卡顿掉帧问题解决办法 2022年8月1日
2022年最新的Android面试大厂必考174题(附带详细答案)
MySQL读写分离的三种实现方案
ADS 2023 下载链接
Introduction to Cosine Distance
设备树基本原理与操作方法
C#将位图旋转90度
国产虚拟化云宏CNware WinStack安装体验-5 开启集群HA
力扣刷题之求两数之和
【夜莺监控方案】08-监控msyql集群(prometheuse+n9e+mysqld_exporter)
Kettle 读取 Excel 数据输出到 Oracle 详解
【微信小程序】NFC 标签打开小程序
MySQL超详细安装教程 手把手教你安装MySQL到使用MySQL 最简单的MySQL安装方式,这种方式装,卸载也简单
LeetCode 952. Calculate Maximum Component Size by Common Factor
Power button brush the topic of merging two orderly array