如何在数组中查找重复项并显示它们出现的次数?

32

我正在编写一段代码,用于从数组中打印出重复的整数及其出现次数。我不允许使用LINQ,只能使用简单的代码。我认为我已经接近成功了,但是对如何获得正确的输出感到困惑:

class Program
{
    static void Main(string[] args)
    {              
        int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
        int count = 1;
        for (int i = 0; i < array.Length; i++)
        {
            for (int j = i; j < array.Length - 1 ; j++)
            {

               if(array[j] == array[j+1])
                  count = count + 1;
            }
            Console.WriteLine("\t\n " + array[i] + "occurse" + count);
            Console.ReadKey();
        }
    }
}
14个回答

0

int[] arr = { 1, 2, 3, 2, 4, 5, 2, 4 };

的意思是定义了一个整型数组,包含元素:1、2、3、2、4、5、2和4。
    var duplicates = arr.GroupBy(x => x)
          .Where(g => g.Count() > 1)
          .Select(y => new { Item = y.Key, Count = y.Count() })
          .ToList();

    Console.WriteLine(String.Join("\n", duplicates));

0
using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    /// <summary>
    /// How do you find the duplicate number on a given integer array?
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };

            Dictionary<int, int> duplicates = FindDuplicate(array);

            Display(duplicates);

            Console.ReadLine();
        }

        private static Dictionary<T, int> FindDuplicate<T>(IEnumerable<T> source)
        {
            HashSet<T> set = new HashSet<T>();
            Dictionary<T, int> duplicates = new Dictionary<T, int>();

            foreach (var item in source)
            {
                if (!set.Add(item))
                {
                    if (duplicates.ContainsKey(item))
                    {
                        duplicates[item]++;
                    }
                    else
                    {
                        duplicates.Add(item, 2);
                    }
                }
            }

            return duplicates;
        }

        private static void Display(Dictionary<int, int> duplicates)
        {
            foreach (var item in duplicates)
            {
                Console.WriteLine($"{item.Key}:{item.Value}");
            }
        }
    }
}

-1

这种方法经过修正后将会给出正确的输出(虽然效率非常低,但除非你需要大规模扩展,否则不是问题)。

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int count = 0;
    for (int j = 0; j < array.Length ; j++)
    {
       if(array[i] == array[j])
          count = count + 1;
    }
    Console.WriteLine("\t\n " + array[i] + " occurs " + count);
    Console.ReadKey();
}

我在下面的原始代码中数了5个错误。

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;                                   // 1. have to put "count" in the inner loop so it gets reset
                                                 // 2. have to start count at 0
for (int i = 0; i < array.Length; i++)
{
    for (int j = i; j < array.Length - 1 ; j++)  // 3. have to cover the entire loop
                                                 // for (int j=0 ; j<array.Length ; j++)
    {
       if(array[j] == array[j+1])                // 4. compare outer to inner loop values
                                                 // if (array[i] == array[j])
          count = count + 1;
    }
    Console.WriteLine("\t\n " + array[i] + "occurse" + count);
                                                 // 5. It's spelled "occurs" :)
    Console.ReadKey();
}

编辑

为了更好的方法,使用一个字典来跟踪计数。这样可以只循环一次数组,并且不会将重复计数打印到控制台。

var counts = new Dictionary<int, int>();
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int currentVal = array[i];
    if (counts.ContainsKey(currentVal))
        counts[currentVal]++;
    else
        counts[currentVal] = 1;
}
foreach (var kvp in counts)
    Console.WriteLine("\t\n " + kvp.Key + " occurs " + kvp.Value);

-1
 class Program
{
    static void Main(string[] args)
    {
        int[] arr = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
        List<int> nums = new List<int>();
        List<int> count = new List<int>();
        nums.Add(arr[0]);
        count.Add(1);
        for (int i = 1; i < arr.Length; i++)
        {

            if(nums.Contains(arr[i]))
            {
                count[nums.IndexOf(arr[i])] += 1;
            }
            else
            {
                nums.Add(arr[i]);
                count.Add(1);
            }
        }

        for(int x =0; x<nums.Count;x++)
        {
            Console.WriteLine("number:"+nums[x] +"Count :"+ count[x]);
        }
        Console.Read();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接