c# - 在数组中查找升序重复对

标签 c# algorithm

给定一个索引为零的数组 A 和 N 个整数,找到数组中不同位置的相等元素。一对索引 (P,Q) 使得 0 <= P < Q < N 使得 A[P] = A[Q]。我的算法如下,但我正在寻找 O(N*logN) 的解决方案。

    public int solution(int[] A)
    {
        int N = A.Length;            
        int count = 0;

        for (int j = 0; j < N; j++)
        {
            count += FindPairs(A[j], j, A);
        }

        return count;
    }

    public int FindPairs(int item, int ci, int[] A)
    {
        int len = A.Length;
        int counter=0;
        int k = ci+1;
        while (k < len)
        {
            if (item == A[k])
                counter++;
            k++;
        }
        return counter;
    }

最佳答案

从您的代码来看,目标似乎是返回 A 中递增重复对的计数。 .

我们观察到如果有m数字 x 的出现次数在 A , 然后是值 x 的递增重复对数是m choose 2 , 或 m (m - 1) / 2 .

所以,我们总结m (m - 1) / 2对于每个独特的 x ,给了我们答案。

在伪代码中,这看起来像:

count = new Dictionary();
foreach a in A {
    count[a]++;
}
total = 0;
foreach key, value in count {
    total += value * (value - 1) / 2;
}
return total;

这个算法是O(N) .

关于c# - 在数组中查找升序重复对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704355/

相关文章:

php - 二维装箱 : Why are my images overlapping?

java - Bellman Ford 的负循环算法

algorithm - 在 O(n) 时间内查找 log n 个最大条目

c# - Entity Framework - 使用 Web.Config 连接字符串

c# - 避免泛型函数中的超出范围问题

c# - 如何找出两个字符串数组是否等于另一个

c - 为什么我的 C 语言 GCD 程序没有运行?

algorithm - 二叉树的密度

c# - NHibernate 将缓存实体重新附加到不同 session 的正确方法

c# - 使用 Entity Framework Code First 和 DBMigration 时生成 ntext/nvarchar 列