在Int []中搜索重复值

时间:2014-05-07 03:07:56

标签: c# arrays visual-studio-2010

我有一个Int数组,我想搜索最长的重复值,除了零。 Examlple: 输入:

Int[] ip = {0,0,0,0,1,2,0,2,2,2}

输出:

Int[] op = {2,3}

第一个数字是一行中最相同的数字, 第二个数字是它们的数量。

有没有有效的方法呢?

4 个答案:

答案 0 :(得分:1)

我最初误读了这个问题......你想要最长的运行数字,而不是总出现次数。

int? last = null;
int count = 0;
var counts = new List<Tuple<int, int>>();

for (int i = 0; i < ip.Length; i++)
{
    var cur = ip[i];

    if (last == null)
    {
        last = cur;
        count = 1;
        continue;
    }

    if (cur == last)
    {
        count++;
    }
    else
    {
        if (last != 0)
        {
            counts.Add(Tuple.Create(last.Value, count));
        }
        count = 1;
        last = cur;
    }

    if (i == ip.Length-1)
    {
        counts.Add(Tuple.Create(cur, count));
    }
}

var longestRun = counts.Max(x => x.Item2);

答案 1 :(得分:0)

创建hashset并执行类似的操作;

for(int i=0;i<arr.length;i++)
{
if(hashset.contains(arr[i])
{
int number = hashset.get(arr[i]);
number++;
hashset.add(arr[i],number);
}
else
{
hashset.add(arr[i],0);
}

//find max occurrence
int max=0;
int key;
foreach(key in hashset)
{
int occurence = hashset.get(key);
if(occurence > max)
{
max = occurence;
key = hashset.key;
}
}


int max_num = key;
int max_occurence = hashset.get(key);

答案 2 :(得分:0)

生成的词典将包含项目和出现次数

int[] ip = { 0, 0, 0, 0, 1, 2, 0, 2, 2, 2 };
Dictionary<int, int> count = ip.GroupBy(x => x).ToDictionary(g => g.Key,g => g.Count());

答案 3 :(得分:0)

您可以尝试这种方式:

var digitCount = new Dictionary<int, int>();
int lastDigit = 0;

foreach (int i in ip)
{
    //don't count 0 digits
    if(i != 0)
    {
        //if current digit already in dictionary
        if (digitCount.ContainsKey(i))
        {
            //if continous, increment counter for corresponding digit
            if (lastDigit == i)
                digitCount[i] = ++digitCount[i];
            //else reset counter to 1
            else
            {
                digitCount[i] = 1;
            }
        }
        //add current digit to dictionary and set counter value to 1
        else
        {
            digitCount.Add(i, 1);
        }
    }

    lastDigit = i;
}

//get dictionay item having largest value
Console.WriteLine(digitCount.OrderByDescending(o => o.Value).First());