int数组中的重复值(最佳性能)

时间:2014-05-17 10:35:56

标签: c# arrays performance language-agnostic duplicates

我有一组数字,它们有一些重复的值。 我想找到前两个重复的数字。

真正的问题是它必须具有最佳性能而且我无法使用LINQ它必须是经典代码。

真正的问题是关于最佳性能,所以它意味着最好的答案是最快的语言和最快的算法。

我在C#中尝试过:

        int[] numbers = {5, 2, 10, 18, 55, 100, 10, 50, 23, 6, 14, 25, 12};
        int result1 = -1;
        int result2 = -1;
        for (int i = 0; i < numbers.Length; i++)
        {
            for (int j = 0; j < numbers.Length; j++)
            {
                if (numbers[j] == numbers[i] & i != j)
                {
                    result2 = j;
                    result1 = i;
                    J = numbers.Length;  //this will cause loop exit.
                    i = numbers.Length;  //this will cause first loop to exit.
                }
            }
        }

        Console.Write("The result of search is {0} and {1}", result1, result2);
        Console.ReadLine();

我将感谢任何答案;)

1 个答案:

答案 0 :(得分:3)

使用字典存储数字以及找到它们的位置,当您找到字典中存在的数字时,您将获得副本及其位置。在字典中添加和定位项是O(1)操作,因此algorighm是O(n)操作:

int[] numbers = { 5, 2, 10, 18, 55, 100, 10, 50, 23, 6, 14, 25, 12 };
Dictionary<int, int> found = new Dictionary<int,int>();
int result1 = -1, result2 = -1;
for (int i = 0; i < numbers.Length; i++) {
  int number = numbers[i];
  int pos;
  if (found.TryGetValue(number, out pos)) {
    result1 = pos;
    result2 = i;
    break;
  }
  found.Add(number, i);
}
Console.Write("The result of search is {0} and {1}", result1, result2);
Console.ReadLine();

对于某些其他性能,您可以为字典中可能需要的所有项目预分配空间。这在平均情况下使用了更多的内存,但是当字典增长时不会重复分配更多的空间:

Dictionary<int, int> found = new Dictionary<int,int>(numbers.Length);