Last active
February 13, 2019 15:30
-
-
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/ 투 포인터
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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