2009-03-05 24 views
7

我在计算数组中的唯一值时遇到了问题,我需要这样做而不重新排列数组元素。如何在不重新排列数组元素的情况下计算数组中的唯一数字?

我该如何做到这一点?

int numberOfElements = myArray.Distinct().Count(); 

非LINQ:

+1

是本次作业? – 2009-03-05 05:36:20

+0

he he kinda; P .... – jarus 2009-03-05 05:40:56

+0

作业没什么问题......只要你不回答问题就好了。 (即,采取答案,并使*更好*)。 – Arafangion 2009-03-05 06:08:53

回答

15

如果你有.NET 3.5,你可以很容易地通过LINQ实现这一

List<int> uniqueValues = new List<int>(); 
for(int i = 0; i < myArray.Length; ++i) 
{ 
    if(!uniqueValues.Contains(myArray[i])) 
     uniqueValues.Add(myArray[i]); 
} 
int numberOfElements = uniqueValues.Count; 
6

这是一个更为有效的非LINQ的实现。

 var array = new int[] { 1, 2, 3, 3, 3, 4 }; 
     // .Net 3.0 - use Dictionary<int, bool> 
     // .Net 1.1 - use Hashtable 
     var set = new HashSet<int>(); 
     foreach (var item in array) { 
      if (!set.Contains(item)) set.Add(item); 
     } 
     Console.WriteLine("There are {0} distinct values. ", set.Count); 
0

应该只计算不同的值还是应计算数组中的每个数(例如“数5包含3次”)?

第二个要求可以通过计数排序算法的启动步骤来实现。
这将是这样的:

  • 构建一组其中索引/键是 要被计数
  • 一个键被连接到用于保持键的OCCURENCES 的数目的变量的元件元件
  • 迭代阵列关键的
    • 增量值(数组[索引])

问候

1

O(n)的运行时间MAX_VALUE存储器使用

boolean[] data = new boolean[maxValue]; 
for (int n : list) { 
    if (data[n]) counter++ 
    else data[n] = true; 
} 
相关问题