[LeetCode] Distinct Numbers in Each Subarray

1852. Distinct Numbers in Each Subarray

Given an integer array nums and an integer k, you are asked to construct the array ans of size n-k+1 where ans[i] is the number of distinct numbers in the subarray nums[i:i+k-1] = [nums[i], nums[i+1], …, nums[i+k-1]].

Return the array ans.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> distinctNumbers(vector<int>& A, int k) {
unordered_map<int, int> freq;
vector<int> res;
for(int i = 0; i < k - 1; i++)
freq[A[i]]++;
int n = A.size(), l = 0, r = k - 1;
while(r < n) {
freq[A[r++]]++;
res.push_back(freq.size());
if(--freq[A[l++]] == 0)
freq.erase(A[l-1]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/28/PS/LeetCode/distinct-numbers-in-each-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.