[InterviewBit] Distinct Numbers in Window

Distinct Numbers in Window

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
vector<int> Solution::dNums(vector<int> &A, int B) {
vector<int> res;
int now = 0;
unordered_map<int, int> freq;
for(int i = 0; i < A.size(); i++) {
if(++freq[A[i]] == 1) now += 1;
if(i >= B) {
if(--freq[A[i-B]] == 0) now -= 1;
}
if(i >= B - 1) res.push_back(now);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/12/PS/interviewbit/distinct-numbers-in-window/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.