The Most frequent Number in an array

后端 未结 9 1605
粉色の甜心
粉色の甜心 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 14:55

    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.

    0 讨论(0)
  • 2021-01-17 14:55

    From a software engineering standpoint, I would expect a function called MostFreq to return the element with the highest frequency - not the frequency itself. I would switch your out and return values.

    0 讨论(0)
  • 2021-01-17 14:57

    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()};
    
    0 讨论(0)
  • 2021-01-17 15:03

    Lets suppose the array is as follows :

    int arr[] = {10, 20, 10, 20, 30, 20, 20,40,40,50,15,15,15};
    
    int max = 0;
    int result = 0;
    Map<Integer,Integer> map = new HashMap<>();
    
    for (int i = 0; i < arr.length; i++) {
        if (map.containsKey(arr[i])) 
            map.put(arr[i], map.get(arr[i]) + 1);
        else
            map.put(arr[i], 1);
        int key = map.keySet().iterator().next();
        if (map.get(key) > max) {
            max = map.get(key) ;
            result = key;
        }
    }
    System.out.println(result);
    

    Explanation:

    In the above code I have taken HashMap to store the elements in keys and the repetition of the elements as values. We have initialized variable max = 0 ( max is the maximum count of repeated element) While iterating over elements We are also getting the max count of keys.

    The result variable returns the keys with the mostly repeated.

    0 讨论(0)
  • 2021-01-17 15:05

    Here's an example how you could do it without LINQ and no dictionaries and lists, just two simple nested loops:

    public class MostFrequentNumber
    {
        public static void Main()
        {
            int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    
            int counter = 0;
            int longestOccurance = 0;
            int mostFrequentNumber = 0;
    
            for (int i = 0; i < numbers.Length; i++)
            {
                counter = 0;
    
                for (int j = 0; j < numbers.Length; j++)
                {
                    if (numbers[j] == numbers[i])
                    {
                        counter++;
                    }
                }
    
                if (counter > longestOccurance)
                {
                    longestOccurance = counter;
                    mostFrequentNumber = numbers[i];
                }
            }
    
            Console.WriteLine(mostFrequentNumber);
            //Console.WriteLine($"occured {longestOccurance} times");
        }
    }
    

    You get the value of the most frequently occurring number, and (commented) you could get also the numbers of the occurrences. I know I have an "using Linq;", that's just to convert the initial input string to an int array and to spare a couple of lines and a parsing loop. Algorithm is fine even without it, if you fill the array the "long" way...

    0 讨论(0)
  • 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<Int32,Int32> bucket = new Dictionary<Int32,Int32>();
                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);
    
            }
        }
    
    0 讨论(0)
提交回复
热议问题