【发布时间】:2020-05-11 16:31:15
【问题描述】:
给定一个大小为 N 的数组 A[] 和一个整数 K。你的任务是完成函数 countDistinct(),它打印数组 A[] 中大小为 k 的所有窗口中不同数字的计数。
Constraints:
1 <= T <= 100
1 <= N <= K <= 105
1 <= A[i] <= 105 , for each valid i
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two integers N and K. Then in the next line are N space separated values of the array A[].
Output:
For each test case in a new line print the space separated values denoting counts of distinct numbers in all windows of size k in the array A[].
Example(To be used only for expected output):
Input:
2
7 4
1 2 1 3 4 2 3
3 2
4 1 1
Output:
3 4 4 3
2 1
解决办法:
void countDistinct(int A[], int k, int n) {
map<int, int> hash;
int cnt=0;
for(int i=0;i<n;i++) {
if(i<k){
hash[A[i]]++;
}
if(i==k-1) {
cout<<hash.size()<<" ";
}
if(i>=k){
if(hash[A[i-k]]==1){
hash.erase(A[i-k]);
} else {
hash[A[i-k]]--;
}
hash[A[i]]++;
cout<<hash.size()<<" ";
}
}
}
其中 A[] 是数组,n 是数组的大小,k 是窗口的大小。 算法: 1. 使用哈希映射来存储元素计数,直到 i==k。 2.当i==k时,要么递减要么擦除map中的A[i-k]个计数;也增加 A[i] 的计数。 3. 打印窗口 k 中不同计数的哈希图大小。
我使用的算法是 O(n),但是 geeksforgeeks 给出了 Time Limit Exceeded 错误。 我哪里出错了?
【问题讨论】:
-
也许他们希望你使用数组而不是地图?
-
感谢@DeepakTatyajiAhire
标签: algorithm algorithmic-trading array-algorithms