博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode题解(0992):K个不同呢的子数组(Python)
阅读量:1901 次
发布时间:2019-04-26

本文共 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

转载地址:http://uczcf.baihongyu.com/

你可能感兴趣的文章
Qt远程连接MySql数据库
查看>>
Windows下Qt的MYSQL数据库开发步骤
查看>>
QtCreator中常用快捷键总结
查看>>
QT样式表编写参考文档
查看>>
Qt样式表的使用
查看>>
Visual Studio中最常用的13个快捷键
查看>>
Qt下使用的静态链接库 *.lib转化为mingw使用的.a格式的静态库
查看>>
Qt调用VS第三方库
查看>>
vs2008+Qt+MySql环境搭建及提示"Driver not load"的原因分析
查看>>
LInmake NK : fatal error LNK1104: 无法打开文件“D:\MySQL\lib.obj”
查看>>
未来物联网发展的十大趋势
查看>>
Python库大全,建议收藏留用!
查看>>
Python之父:Python 4.0可能不会有了
查看>>
嵌入式开发中需要用到设计模式吗?
查看>>
C语言指针必看!
查看>>
指针的应用,一个简单例子讲清楚你多年的糊涂
查看>>
vue 指令 之 v-if、v-else-if、v-else
查看>>
vue 指令 之 v-show
查看>>
html 引入 vue.js
查看>>
vue 环境搭建 无坑点
查看>>