The Most frequent Number in an array

Assuming you can't use LINQ, I'd probably approach the algorithm like this:

  • Create Key/Value dictionary
  • Iterate your array, add a key the dictionary for each unique elem, increment the value each time that element is repeated.
  • Walk the dictionary keys, and return the elem with the highest value.

This isn't a great solution but it is simple, ContainsKey is an O(1) lookup, so you'll be at most iterating your array twice.


LINQ it up. I know this is in VB but you should be able to convert it to C#:

Dim i = From Numbers In ints _
            Group Numbers By Numbers Into Group _
            Aggregate feq In Group Into Count() _
            Select New With {.Number = Numbers, .Count = Count}

EDIT: Now in C# too:

var i = from numbers in M
                group numbers by numbers into grouped
                select new { Number = grouped.Key, Freq = grouped.Count()};

Tags:

C#

Algorithm