C# 数组中出现频率最高的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/279359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The Most frequent Number in an array
提问by
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 worte what do you think ? is there a better way to do it?
我有这个 Array 我写了一个函数 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);
}
=====
======
in the class Mymath
在 Mymath 课堂上
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);
}
采纳答案by Nathan W
LINQ it up. I know this is in VB but you should be able to convert it to C#:
LINQ 起来。我知道这是在 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}
EDIT: Now in C# too:
编辑:现在也在 C# 中:
var i = from numbers in M
group numbers by numbers into grouped
select new { Number = grouped.Key, Freq = grouped.Count()};
回答by Tom Ritter
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.
从软件工程的角度来看,我希望名为 MostFreq 的函数返回具有最高频率的元素 - 而不是频率本身。我会换掉你并返回值。
回答by FlySwat
Assuming you can't use LINQ, I'd probably approach the algorithm like this:
假设你不能使用 LINQ,我可能会像这样处理算法:
- 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.
这不是一个很好的解决方案,但它很简单,ContainsKey 是一个 O(1) 查找,因此您最多将迭代数组两次。
回答by jTresidder
You could eliminate the sort you do at the start by iterating the entire array once, keeping a count of how many times you come across each value in a temporary array, and then iterating the temporary array for the highest number. You could keep both the highest frequency count and the most frequent item throughout, too.
您可以通过迭代整个数组一次来消除您在开始时所做的排序,记录您遇到临时数组中每个值的次数,然后迭代临时数组以获得最高数字。您也可以始终保持最高频率计数和最频繁的项目。
Different sorts have different efficiencies on different types of data, of course, but this would be a worst case of just two iterations.
当然,不同类型对不同类型的数据有不同的效率,但这将是仅两次迭代的最坏情况。
Edit: Apologies for the repeat... 'Tweren't there when I started :)
编辑:为重复道歉......'我开始时不在那里:)
回答by wally
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];
回答by AJIT AGARWAL
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();
}
}
}
回答by Pazzo
Here's an example how you could do it without LINQ and no dictionaries and lists, just two simple nested loops:
这是一个示例,您可以在没有 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");
}
}
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...
您可以获得最频繁出现的数字的值,并且(评论)您还可以获得出现次数。我知道我有一个“使用 Linq;”,这只是将初始输入字符串转换为 int 数组并节省几行和解析循环。算法即使没有它也很好,如果你以“长”的方式填充数组......
回答by AnthonyLambert
Done in 1 pass....
1 次完成....
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);
}
}