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


首先,使用重複元素設定陣列。

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

更新於: 22-Jun-2020

8K+ 閱讀量

開啟您的 職業生涯

完成課程以獲取認證

立即開始
廣告
© . All rights reserved.