代码之家  ›  专栏  ›  技术社区  ›  Brandon

数组中最常用的数

  •  11
  • Brandon  · 技术社区  · 17 年前

    我有一个数组,我写了一个函数MostFreq,它接受一个整数数组并返回2个值:数组中频率越高的数字和它的频率检查这段代码,你觉得怎么样?有更好的方法吗?

    static void Main()
    { 
        int [] M={4,5,6,4,4,3,5,3};
        int x;
        int f=MyMath.MostFreq(M,out x );
        console.WriteLine("the most Frequent Item = {0} with frequency = {1}",x,f);
    }
    

    =====

    在我的数学课上

    public static int MostFreq(int[] _M, out int x)
    {
        //First I need to sort the array in ascending order
        int Max_Freq, No_Freq, i, k;
        Array.Sort(_M);                         
        k = _M[0];
        Max_Freq = 0; i = 0; x = 0;
        while (i < _M.Length)
        {
            //No_Freq= the frequency of the current number
            No_Freq = 0;
            //X here is the number which is appear in the array Frequently 
            while (k == _M[i])
            {
                No_Freq++;
                i++;
                if (i == _M.Length) 
                    break;
            }
            if (No_Freq > Max_Freq)
            {
                //so it will be printed the same
                Max_Freq = No_Freq;
                x = k;
            }
            if (i < _M.Length) k = _M[i];
        }
        return (Max_Freq);
    }
    
    8 回复  |  直到 11 年前
        1
  •  9
  •   Nathan W    17 年前

    把它弄起来。我知道这是在VB中,但您应该能够将其转换为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}
    

    编辑:现在也在C#中:

    var i = from numbers in M
                    group numbers by numbers into grouped
                    select new { Number = grouped.Key, Freq = grouped.Count()};
    
        2
  •  6
  •   FlySwat    17 年前

    • 创建键/值字典
    • 迭代数组,为每个唯一元素在字典中添加一个键,每次重复该元素时增加值。
    • 遍历字典键,并返回具有最高值的元素。

    这不是一个很好的解决方案,但它很简单,ContainsKey是一个O(1)查找,因此您最多将数组迭代两次。

        3
  •  3
  •   Tom Ritter    17 年前

    从软件工程的角度来看,我希望一个名为MostFreq的函数返回具有最高频率的元素,而不是频率本身。我会切换出你的值并返回值。

        4
  •  1
  •   jTresidder    17 年前

    您可以通过迭代整个数组一次,记录在临时数组中遇到每个值的次数,然后迭代临时数组以获得最大值来消除开始时所做的排序。您也可以始终保持最高频率计数和最频繁的项目。

    当然,不同种类的数据对不同类型的数据具有不同的效率,但这将是两次迭代的最坏情况。

    编辑:为重复道歉…'我刚开始的时候还没到:)

        5
  •  0
  •   AJIT AGARWAL    9 年前
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MostFrequentElement
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] array = new int[] { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3, 1, 1, 7, 7, 7, 7, 7 };
                Array.Sort(array, (a, b) => a.CompareTo(b));
                int counter = 1;
                int temp=0 ;
    
                List<int> LOCE = new List<int>();
                foreach (int i in array)
                {
                    counter = 1;
                    foreach (int j in array)
    
    {
                        if (array[j] == array[i])
                        {
                            counter++;
                        }
                        else {
                        counter=1;
                        }
                        if (counter == temp)
                        {
                            LOCE.Add(array[i]);
                        }
                        if (counter > temp)
                        {
                            LOCE.Clear();
                            LOCE.Add(array[i]);
                            temp = counter;
    
                        }
                    }
    
                }
                foreach (var element in LOCE)
                {
                    Console.Write(element + ",");
                }
                Console.WriteLine();
                Console.WriteLine("(" + temp + " times)");
                Console.Read();
            }
        }
    }
    
        6
  •  0
  •   Pazzo    9 年前

    下面是一个示例,您可以在没有LINQ、没有字典和列表、只有两个简单的嵌套循环的情况下完成此操作:

    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");
        }
    }
    

    您可以获得最频繁出现的数字的值,并且(注释)还可以获得出现的数字。 我知道我有一个“using Linq;”,它只是将初始输入字符串转换为int数组,并留出几行代码和一个解析循环。即使没有它,算法也很好,如果你以“长”的方式填充数组。。。

        7
  •  0
  •   AnthonyLambert    8 年前

    一次完成。。。。

    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);
    
            }
        }
    
        8
  •  0
  •   Matt Ke Alex Santos    6 年前

    假设数组如下所示:

    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);
    

    说明:

    在上面的代码中,我使用HashMap将元素存储在键中,并将元素的重复作为值。我们已经初始化了变量max=0(max是重复元素的最大计数),同时在元素上迭代,我们也得到了键的最大计数。

    result变量返回重复次数最多的键。

        9
  •  0
  •   BorisSh    5 年前
    int[] arr = { 4, 5, 6, 4, 4, 3, 5, 3 };
    var gr = arr.GroupBy(x => x).OrderBy(x => x.Count()).Last();
    Console.WriteLine($"The most Frequent Item = {gr.Key} with frequency = {gr.Count()}"); // The most Frequent Item = 4 with frequency = 3
    
        10
  •  -1
  •   Kijewski Jim    14 年前
    int count = 1;
    int currentIndex = 0;
    for (int i = 1; i < A.Length; i++)
    {
        if (A[i] == A[currentIndex])
            count++;
        else
            count--;
        if (count == 0)
        {
            currentIndex = i;
            count = 1;
        }
    }
    
    int mostFreq = A[currentIndex];