2017-02-27 36 views
4

我想從數組中找出第k個最常見的元素,我能夠找到最常見的元素,但我不知道如何找到第k個常見元素。從c中的給定整數數組中獲取第k個公共元素

我想這樣的:

private static int KthCommonElement(int[] a, int k) 
{ 
    var counts = new Dictionary<int, int>(); 
    foreach (int number in a) 
    { 
     int count; 
     counts.TryGetValue(number, out count); 
     count++; 
     //Automatically replaces the entry if it exists; 
     //no need to use 'Contains' 
     counts[number] = count; 
    } 
    int mostCommonNumber = 0, occurrences = 0; 
    foreach (var pair in counts) 
    { 
     if (pair.Value > occurrences) 
     { 
      occurrences = pair.Value; 
      mostCommonNumber = pair.Key; 
     } 
    } 
    Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences); 

    return mostCommonNumber; 
} 
+0

這個效率如何?它是否需要比全面排序更高效? –

回答

8

您可以通過他們的occurence元素進行排序,並採取第k個元素:

int[] orderedByOccurence = a.OrderByDescending(i => counts[i]).ToArray(); 
if (orderedByOccurence.Length > k) 
    Console.WriteLine($"{k}th most common element: {orderedByOccurence[k]}); 

但正如亞當在評論中指出的那樣,你可以使用GroupBy縮短代碼:

private static int KthCommonElement(int[] a, int k) 
{ 
    if (a == null) throw new ArgumentNullException(nameof(a)); 
    if (a.Length == 0) throw new ArgumentException(); 
    if (k < 0) throw new ArgumentOutOfRangeException(); 

    var ordered = a.GroupBy(i => i, (i, o) => new { Value = i, Occurences = o.Count()}) 
        .OrderByDescending(g => g.Occurences) 
        .ToArray(); 

    int index = k; 
    if (ordered.Length <= index) 
    { 
     // there are less than k distinct values in the source array 
     // so add error handling here, either throw an exception or 
     // return a "magic value" that indicates an error or return the last element 
     index = ordered.Length - 1; 
    } 

    var result = ordered[index]; 
    Console.WriteLine("The most common number is {0} and it appears {1} times", 
      result.Value, result.Occurrences); 

    return result.Value; 
}  
+0

如果你想玩它的代碼高爾夫球,也有一種方法可以使用'GroupBy'來統計自己的人數。 –

+0

我覺得在這裏需要一些改進:return ordered [k]; – Dipak

+0

@DipakAkhade你能更具體嗎?有什麼改進? –

相關問題