2017-02-27 4 views
4

Ich möchte herausfinden, die kth am häufigsten Element aus einem Array und ich konnte am häufigsten Element finden, aber ich weiß nicht, wie kth common zu finden.Get kth gemeinsames Element aus gegebenen Integer-Array in C#

Ich habe versucht, wie:

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

Wie effizient muss das sein? Muss es effizienter sein als eine vollständige Sortierung? –

Antwort

8

Sie die Elemente durch ihre Vorkommen sortieren und das k-te Element nehmen:

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

Aber als Adam in den Kommentaren darauf hingewiesen, können Sie kürzen Sie Ihren Code mit 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

Es gibt auch eine Möglichkeit, die Bevölkerung der Grafen selbst mit 'GroupBy' zu machen, wenn Sie damit Code-Golf spielen wollen. –

+0

Ich denke, dass hier eine Verbesserung nötig ist: Rückkehr bestellt [k]; – Dipak

+0

@DipakAkhade können Sie genauer sein? Welche Art von Verbesserung? –

Verwandte Themen