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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP