The Most frequent Number in an array

后端 未结 9 1613
粉色の甜心
粉色の甜心 2021-01-17 14:14

I have this Array i wrote a function MostFreq that takes an array of integers and return 2 values : the more frequent number in the array and its frequency check this code i

9条回答
  •  花落未央
    2021-01-17 15:05

    Done in 1 pass....

    public class PopularNumber
        {
            private Int32[] numbers = {5, 4, 3, 32, 6, 6, 3, 3, 2, 2, 31, 1, 32, 4, 3, 4, 5, 6};
    
            public PopularNumber()
            {
                Dictionary bucket = new Dictionary();
                Int32 maxInt = Int32.MinValue;
                Int32 maxCount = 0;
                Int32 count;
    
                foreach (var i in numbers)
                {
                    if (bucket.TryGetValue(i, out count))
                    {
                        count++;
                        bucket[i] = count;
                    }
                    else
                    {
                        count = 1;
                        bucket.Add(i,count);
                    }
    
                    if (count >= maxCount)
                    {
                        maxInt = i;
                        maxCount = count;
                    }
    
                }
    
                Console.WriteLine("{0},{1}",maxCount, maxInt);
    
            }
        }
    

提交回复
热议问题