2012-09-12 93 views
0

我想要查找整數數組中前3個最大重複數字?若要查找整數數組中前3個最大重複數字

下面是一段代碼,我都試過,但我無法找到期望的結果:

static void Main(string[] args) 
    { 

     int[,] numbers = { 
          {1, 2, 0, 6 }, 
          {5, 6, 7, 0 }, 
          {9, 3, 6, 2 }, 
          {6, 4, 8, 1 } 
         };   
     int count = 0; 
     List<int> checkedNumbers = new List<int>(); 
     foreach (int t in numbers) 
     { 
      if (!checkedNumbers.Contains(t)) 
      { 
       foreach (int m in numbers)     
       { 
        if (m == t)       
         { 
         count++; 
         } 
       } 
       Console.WriteLine("Number {0} is Repeated {1} Times ", t, count); 
       count = 0; 
       checkedNumbers.Add(t); 
      }   
     } 
     Console.ReadLine(); 
    } 
+0

我發佈了我試過的代碼。如果我做錯了什麼,只是看一看,並建議我? –

+0

請檢查我的答案與您的代碼 –

回答

5

然後,您可以OrderByDescending根據各組的計數使用GroupBy從LINQ:

var result = list.GroupBy(i => i) 
       .OrderByDescending(g => g.Count()) 
       .Select(g => g.Key) 
       .Take(3); 

編輯:你的代碼,你可以使用OfType扁平化的矩陣,然後使用上面的代碼:

int[,] numbers = { 
         {1, 2, 0, 6 }, 
         {5, 6, 7, 0 }, 
         {9, 3, 6, 2 }, 
         {6, 4, 8, 1 } 
       }; 

var list = numbers.OfType<int>(); 
1
int[] numbers = {1, 2, 3, 5, 6, 32, 2, 4, 42, 2, 4, 4, 5, 6, 3, 4}; 
var counts = new Dictionary<int, int>(); 
foreach (var number in numbers) 
{ 
    counts[number] = counts[number] + 1; 
} 
var top3 = counts.OrderByDescending(x => x.Value).Select(x => x.Key).Take(3); 
1

提示:

你可以的幫助下做到這一點LINQ。
這是找到最frequest發生的歷史元素的代碼: -

List<int> list = new List<int>() { 1,1,2,2,3,4,5 }; 

// group by value and count frequency 
var query = from i in list 
      group i by i into g 
      select new {g.Key, Count = g.Count()}; 

// compute the maximum frequency 
int frequency = query.Max(g => g.Count); 

// find the values with that frequency 
IEnumerable<int> modes = query 
           .Where(g => g.Count == frequency) 
           .Select(g => g.Key); 

// dump to console 
foreach(var mode in modes) { 
    Console.WriteLine(mode); 
} 

以同樣的方式,你可以找到另外兩個也。

1

我看到現有的答案都沒有提供解釋,所以我會盡力解釋。

您需要做的是統計每個項目在陣列中出現的次數。要做到這一點,有各種方法(字典,LINQ等)。也許這將是最容易使用的包含數字的字典,以及它如何出現次數:

int numbers[] = {1, 3, 6, 10, 9, 3, 3, 1, 10} ; 
Dictionary<int, int> dic = new Dictionary<int, int>(); 

現在通過數字的每一個元素迭代,並把它添加到字典中。如果已經添加,只需增加計數值即可。

foreach (var i in numbers) 
{ 
    dic[i]++; // Same as dic[i] = dic[i]+1; 
} 

,如果它不存在,所以我們可以簡單地做dic[i]++;

接下來會自動添加一個新項目的字典,我們需要得到最高的3個值。再次,有很多方法可以做到這一點,但最簡單的方法就是對其進行分類。

var sorted_dic = dic.OrderByDescending(x => x.Value); 

現在sorted_dic第3項將是您正在尋找的3個值。 有多種方法得到的只有這3個,例如使用Take方法:

var first_3 = sorted_dic.Take(3); 

現在,你可以通過這3個值重複,例如打印在屏幕上:

foreach (var i in first_3) 
{ 
    Console.Write("{0} appeared {1} times.", i.Key, i.Value); 
}