LeetCode题解(0992):K个不同呢的子数组(Python)
发布日期:2021-06-29 20:09:38
浏览次数:3
分类:技术文章
本文共 1159 字,大约阅读时间需要 3 分钟。
题目:(困难)
标签:哈希表、数组、双指针、滑动窗口
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( N ) O(N) O(N) | O ( N ) O(N) O(N) | 724ms (44.79%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
class Solution: def subarraysWithKDistinct(self, A: List[int], K: int) -> int: i1, i2, i3 = 0, 0, 0 # 有K个不同的数组的开头,有K-1个不同的数组的开头,两个数组的结尾 count1, count2 = collections.Counter(), collections.Counter() # i1到i3的数组的情况,i2到i3的数组的情况 ans = 0 size = len(A) while i3 < size: # 移动数组右侧边缘指针 ch3 = A[i3] count1[ch3] += 1 count2[ch3] += 1 # 移动i1到i3的数组左侧边缘指针 while i1 <= i3 and len(count1) > K: ch1 = A[i1] count1[ch1] -= 1 if count1[ch1] == 0: del count1[ch1] i1 += 1 # 移动i2到i3的数组左侧边缘指针 while i2 <= i3 and len(count2) > K - 1: ch2 = A[i2] count2[ch2] -= 1 if count2[ch2] == 0: del count2[ch2] i2 += 1 # 累加结果 if len(count1) == K and len(count2) == K - 1: ans += i2 - i1 i3 += 1 return ans
转载地址:https://dataartist.blog.csdn.net/article/details/109842521 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月11日 02时34分40秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Hadoop学习笔记:二、Hadoop环境安装配置
2019-04-30
彻底搞懂Python一切皆对象!!!
2019-04-30
【成长之路】本科比赛经验分享
2019-04-30
【成长之路】本科比赛作品设计经验分享
2019-04-30
Qt设置QTextEdit和QLabel的字体颜色
2019-04-30
Qt phonon多媒体框架
2019-04-30
linux下Mplayer安装与设置指南(以及如何加载显示中文字幕)
2019-04-30
Qt多媒体播放phonon
2019-04-30
Mysql group by 详解
2019-04-30
Qt学习笔记
2019-04-30
Qt主题风格设置
2019-04-30
android问题汇总-待解决
2019-04-30
sql数据库语句问题及总结
2019-04-30
sql数据库触发器
2019-04-30
Could not reserve enough space
2019-04-30
2020-09-27 优秀的毕业生 罗升阳
2019-04-30
定时器ScheduledExecutorService与Timer
2019-04-30
【原文翻译】Android应用程序集成SQLCipher实现SQLite加密
2019-04-30