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
classSolution { 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; } };