C# 程序查找整数数组中的所有重复元素

csharpprogrammingserver side programming更新于 2025/9/18 21:14:00

首先,设置包含重复元素的数组。

int[] arr = {
   24,
   10,
   56,
   32,
   10,
   43,
   88,
   32
};

现在声明一个 Dictionary 并循环遍历数组以获取重复元素。

var d = new Dictionary < int, int > ();
foreach(var res in arr) {
   if (d.ContainsKey(res))
         d[res]++;
   else
   d[res] = 1;
}

示例

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = {
            24,
            10,
            56,
            32,
            10,
            43,
            88,
            32
         };
         var d = new Dictionary < int, int > ();
         foreach(var res in arr) {
            if (d.ContainsKey(res))
            d[res]++;
            else
            d[res] = 1;
         }
         foreach(var val in d)
         Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
      }
   }
}

输出

24 occurred 1 times
10 occurred 2 times
56 occurred 1 times
32 occurred 2 times
43 occurred 1 times
88 occurred 1 times

相关文章