[英]C# - How many times a specific int value appears in array? No Linq tech
在SO上已经看到许多答案,但是找不到合适的答案。
我需要一种有效的算法或C#中的方法来计算特定int值出现在array中的次数 。 没有Linq 。 数组的大小> = 100,每个元素不大于100
具有以下代码:
for (int i = 0; i < 100; i++) // get each number for counting
{
counter = 0; // zero counter for next number comparison
for (int a = 0; a < array.Length; i++)
{
if (i == array[a])
{
counter++;
if (max < counter) max = counter; // save max-appeared num
}
}
}
它在测试质询中显示为结果消息“由于超时而终止”。 我想这段代码需要很多时间才能解决。 还有其他选择吗?
你可以利用
每个元素不大于100
并将所有频率声明为一个数组 (只能包含101
项目: [0..100]
):
int[] freqs = new int[101];
foreach (var item in array)
freqs[item] += 1;
输出:
for (int i = 0; i < freqs.Length; ++i)
Console.WriteLine("Number {0} appears {1} times", i, freqs[i]);
通常,对于任意大项目,您必须处理dictionary :
Dictionary<int, int> freqs = new Dictionary<int, int>();
foreach (var item in array) {
int v;
if (freqs.TryGetValue(item, out v))
freqs[item] = v + 1;
else
freqs.Add(1);
}
输出(未排序):
foreach (var pair in freqs)
Console.WriteLine("Number {0} appears {1} times", pair.Key, pair.Value);
程序代码:
int[] num = { 1, 1, 1, 3, 3, 4, 5, 6, 7, 0 };
int[] count = new int[10];
//Loop through 0-9 and count the occurances
for (int x = 0; x < 10; x++)
for (int y = 0; y < num.Length; y++)
if (num[y] == x)
count[x]++;
//For displaying output only
for (int x = 0; x < 10; x++)
Console.WriteLine("Number " + x + " appears " + count[x] + " times");
程序输出:
Number 0 appears 1 times
Number 1 appears 3 times
Number 2 appears 0 times
Number 3 appears 2 times
Number 4 appears 1 times
Number 5 appears 1 times
Number 6 appears 1 times
Number 7 appears 1 times
Number 8 appears 0 times
我知道当您所有的同学都完成他们的学业后,您仍在苦苦挣扎的感觉。 我的代码应该足够简单以供您学习。
您可以避免执行两个循环
// Prepare the test array (this is done before entering the counting loop)
Random rnd = new Random();
int[] array = new int[100]; // 100 or whatever....
for (int i = 0; i < array.Length; i++)
array[i] = rnd.Next(1, 101); // 1-100 range
// The max occurences of a number
int maxOccurence = 0;
// The number with the max occurences
int currentMax = 0;
// One bigger to accomodate the 100....
int[] occurrences = new int[array.Length + 1];
// Loop and check on the test array
for (int a = 0; a < array.Length; a++)
{
// The current number to examine
int number = array[a];
// Increment the occurences counter for the number
occurrences[number]++;
// Check if we have a new max....
if (occurrences[number] > maxOccurence)
{
// Save the new leader, both the new max occurence and number
maxOccurence = occurrences[number];
currentMax = number;
}
}
Console.WriteLine(maxOccurence);
Console.WriteLine(currentMax);
但是,这仍然无法检测两个或多个数字是否具有相同的出现次数。
您可以执行以下操作:
var counters = new int[101]; // 0 to 100
var max = 0;
var maxCount = 0;
foreach (var n in input)
{
counters[n] = counters[n] + 1;
if (counters[n] > maxCount)
{
maxCount = counters[n];
max = n;
}
}
return max;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.