当前位置:网站首页>leetcode:98. 统计得分小于 K 的子数组数目【双指针 + 计算子集个数 + 去重】
leetcode:98. 统计得分小于 K 的子数组数目【双指针 + 计算子集个数 + 去重】
2022-06-12 18:36:00 【白速龙王的回眸】
分析
滑动窗口得到所有合法的最大的【l, r】
如果排序后的区间有覆盖的部分需要剪掉覆盖的即可
因为大的区间成立,小的必然成立
所以用滑动窗口找到所有成立的大区间 再求子集 并相邻区间去重即可
Ac code
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
ans = 0
n = len(nums)
l = 0
nowSum = 0
nowLen = 0
myDict = defaultdict(int)
for r in range(n):
nowSum += nums[r]
nowLen += 1
if nowSum * nowLen < k:
myDict[l] = r
else:
while nowSum * nowLen >= k:
nowSum -= nums[l]
nowLen -= 1
l += 1
myDict[l] = r
myList = list(myDict.items())
myList.sort()
#print(myList)
for l, r in myList:
ans += ((r - l + 2) * (r - l + 1)) // 2
for i in range(1, len(myList)):
if myList[i][0] <= myList[i - 1][1]:
l, r = myList[i][0], myList[i - 1][1]
ans -= ((r - l + 2) * (r - l + 1)) // 2
return ans
总结
连续的这种东西滑动窗口永远是个思路
然后发现大的成立小的一定成立
计算一下区间内的子集总数
然后相邻区间去重一下即可
边栏推荐
- Arrays in JS (including leetcode examples) < continuous update ~>
- Problems that the sap Spartacus e-commerce cloud UI shipping method does not display in the unit test environment
- Stack in JS (including leetcode examples) < continuous update ~>
- Review of MySQL (IX): index
- Typescript advanced type (2)
- Vue —— 进阶 vue-router 路由(二)(replace属性、编程式路由导航、缓存路由组件、路由的专属钩子)
- This shift, I still have to go
- 【矩阵论 & 图论】期末考试复习思维导图
- 在思科模拟器Cisco Packet Tracer实现自反ACL
- Interior design style type, rendering 100 invitation code [1a12]
猜你喜欢
Review of MySQL (IX): index
间隔两个月,我的第二次上榜纪念日【2022.6.2】
Two months later, my second listing anniversary [June 2, 2022]
VirtualLab基础实验教程-4.单缝衍射
Partial scratch and corrosion detection of bolts and screws based on Halcon
Common methods and examples of defect detection based on Halcon
MYSQL:Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column
C语言学习——数据在内存中的存储
Difference between rxjs of() and of ({})
VirtualLab基础实验教程-6.闪耀光栅
随机推荐
Stack in JS (including leetcode examples) < continuous update ~>
Random talk about redis source code 90
干货 | 一文搞定 pytest 自动化测试框架(二)
PHP:Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocat
间隔两个月,我的第二次上榜纪念日【2022.6.2】
Arrays in JS (including leetcode examples) < continuous update ~>
深圳3月14日起全市停工停业7天居家办公心得|社区征文
Machine learning series (5): Naive Bayes
Basic SQL statement - select (single table query)
Changes in the third generation dri
Summary of static memory allocation and dynamic memory allocation
Gossip about the 88 of redis source code
Research Report on the overall scale, major manufacturers, major regions, products and applications of Electric Screwdrivers in the global market in 2022
Regression analysis based on elasticnetcv
Typescript type declaration file (III)
Getting started with the go language is simple: read / write lock
CEPH deploy offline deployment of CEPH cluster and error reporting FAQ
JS dichotomy
309. the best time to buy and sell stocks includes the freezing period
2022.6.12-----leetcode. eight hundred and ninety