C# - 特定int值出现在数组中的次数?没有Linq技术

时间:2017-03-19 10:31:12

标签: c# algorithm search

在SO上看到过很多答案,但找不到合适的答案。

我需要一个高效的算法或C#中的方法来计算特定int值在数组中出现的次数没有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
            }   
       }
    }

它显示为结果消息&#34;由于超时终止&#34;在测试挑战中。我想这段代码需要很长时间才能解决。有没有替代方案呢?

4 个答案:

答案 0 :(得分:3)

你可以利用

  

每个元素不大于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<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);

答案 1 :(得分:0)

程序代码:

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

我理解当你所有同学完成他们的时候感觉有多糟糕,而你仍然在苦苦挣扎。我的代码应该足够简单,以便您学习。

答案 2 :(得分:0)

你可以避免执行两个循环

SELECT IICustID, CuFirstNameTx, MAX(IIShipDate_N) AS Expired 
FROM T_IIInvoiceItem
INNER JOIN T_CuCust ON CuCustID=IICustID
GROUP BY IICustID, CuFirstNameTx
HAVING DATEDIFF(d, MAX(IIShipDate_N),GetDate())=30

然而,如果两个或更多个数字具有相同的出现次数,则仍然无法检测到。

答案 3 :(得分:0)

您可以执行以下操作:

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;