C# 程式在整數陣列中查詢所有重複元素


首先,設定包含重複元素的陣列。

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;
}

示例

 實際演示

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

更新日期:22-Jun-2020

8K+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告