【问题标题】:Count distinct elements in every window using hash map使用哈希映射计算每个窗口中的不同元素
【发布时间】: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


【解决方案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)。

因此使用 unordered_map 如下:

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 判决

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多