Skip to content

Instantly share code, notes, and snippets.

@fpdjsns
Last active February 13, 2019 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fpdjsns/1174d3748a24722928c6210b8fecd30f to your computer and use it in GitHub Desktop.
Save fpdjsns/1174d3748a24722928c6210b8fecd30f to your computer and use it in GitHub Desktop.
[leetcode] 992. Subarrays with K Different Integers : https://leetcode.com/problems/subarrays-with-k-different-integers/ 투 포인터
class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
int l = 0;
vector<int> cnt(A.size()+1, 0);
int diffCnt = 0;
int answer = 0;
int tmpAns = 0;
for(int r=0;r<A.size();r++){
int now = A[r];
if(cnt[now] == 0){ // new
// erase diff
if(diffCnt == K){
while(l<r) {
cnt[A[l]]--;
l++;
if(cnt[A[l-1]] == 0)
break;
}
tmpAns = 0;
}else{
diffCnt++;
}
}
cnt[now]++;
if(diffCnt == K){
while(l<r){
if(cnt[A[l]] == 1) break;
cnt[A[l]]--;
l++;
tmpAns++;
}
answer += tmpAns + 1;
}
}
return answer;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment