使用哈希图计算每个窗口中的不同元素。

问题描述 投票:0回答:1

给定一个大小为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

解答:你的任务是完成函数countDistinct(),该函数打印出数组A[]中所有大小为k的窗口中的独特数的数量。

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. 2.当i==k时,在图中递减或删除A[i-k]的计数,同时递增A[i]的计数。打印窗口k中不同计数的哈希图大小。

我使用的算法是O(n),但是geekforgeeks给出了超过时间限制的错误信息,我是不是哪里出错了?

algorithm algorithmic-trading array-algorithms
1个回答
1
投票

可能是使用map的缘故,在map中插入和搜索需要O(log N)时间,而在unordered_map中,这些操作平均需要O(1)时间。另外,我认为N和K在所有测试用例中都接近10^5,所以使用map需要O(T * N * O(log K)),使得时间复杂度在O(100 * 100000 * 17)范围内,即O(1.7*10^8)。

因此使用 无序地图 如下。

void countDistinct(int A[], int k, int n) {
    unordered_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()<<" ";
        }
    }
}

Geeks For Geeks Verdict

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.