2017-02-27 4 views
4

k番目の最も一般的な要素を配列から探したいが、最も一般的な要素を見つけることができたが、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

:よう

は、私が試した


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あなたはより具体的になることができますか?どんな改善? –

関連する問題