LC 992. Subarrays with K Different Integers
2024-09-01 09:45:12
Given an array A
of positive integers, call a (contiguous, not necessarily distinct) subarray of A
good if the number of different integers in that subarray is exactly K
.
(For example, [1,2,3,1,2]
has 3
different integers: 1
, 2
, and 3
.)
Return the number of good subarrays of A
.
Example 1:
Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
Example 2:
Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
Note:
1 <= A.length <= 20000
1 <= A[i] <= A.length
1 <= K <= A.length
Runtime: 128 ms, faster than 100.00% of C++ online submissions for Subarrays with K Different Integers.
Memory Usage: 25 MB, less than 100.00% of C++ online submissions for Subarrays with K Different Integers.
class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
return atMostK(A, K) - atMostK(A,K-);
}
int atMostK(vector<int>& A, int K) {
int i = ,res = ;
unordered_map<int,int> mp;
for(int j=; j<A.size(); j++) {
if(!mp[A[j]]++) K--;
while(K<){
if(!--mp[A[i]]) K++;
i++;
}
res += j - i + ;
}
return res;
}
};
最新文章
- SqlServer 2008登录时报错
- JS事件对象与事件委托
- Mongodb 副本集分片(二)---mongodb副本集部署脚本详解
- 1336 - Sigma Function---LightOj1336
- 统计第一个空字符前面的字符长度(java实现)
- android Baseadapter 和 ViewHolder的使用
- 【socket】TCP 和 UDP 在socket编程中的区别
- JQ each
- 演示基于SDL2.0+FFmpeg的播放器
- Nginx详解八:Nginx基础篇之Nginx请求限制的配置语法与原理
- C++程序设计方法3:函数重写
- 忘记mysql密码处理方案
- angular4-事件绑定
- iOS.UI.UIWindow
- centos中,tomcat项目创建文件的权限
- Splunk 交流
- Spring-profile设置
- 异常信息 Exception
- Delphi编程中使用回车键不换行处理方法!!
- sublime 快捷键 1到9的顺序