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: 12, 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. 1 <= A.length <= 20000
  2. 1 <= A[i] <= A.length
  3. 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;
}
};

最新文章

  1. SqlServer 2008登录时报错
  2. JS事件对象与事件委托
  3. Mongodb 副本集分片(二)---mongodb副本集部署脚本详解
  4. 1336 - Sigma Function---LightOj1336
  5. 统计第一个空字符前面的字符长度(java实现)
  6. android Baseadapter 和 ViewHolder的使用
  7. 【socket】TCP 和 UDP 在socket编程中的区别
  8. JQ each
  9. 演示基于SDL2.0+FFmpeg的播放器
  10. Nginx详解八:Nginx基础篇之Nginx请求限制的配置语法与原理
  11. C++程序设计方法3:函数重写
  12. 忘记mysql密码处理方案
  13. angular4-事件绑定
  14. iOS.UI.UIWindow
  15. centos中,tomcat项目创建文件的权限
  16. Splunk 交流
  17. Spring-profile设置
  18. 异常信息 Exception
  19. Delphi编程中使用回车键不换行处理方法!!
  20. sublime 快捷键 1到9的顺序

热门文章

  1. 第十八篇:简易版web服务器开发
  2. ubuntu 启动图形界面 sudo init 5
  3. about微信小程序
  4. ElementUI2.0组件库el-table表格组件如何自定义表头?
  5. Spring MVC框架及标签库
  6. vb开发最全教程
  7. C#获取资源文件
  8. c++ 构造函数执行顺序
  9. BZOJ2616 SPOJ PERIODNI(笛卡尔树 + DP)
  10. SQL:分区拾忆