关于这个问题网络上的解决方案很多,考虑到时间复杂度,下面是我个人的解决方法:
话不多说直接附上源码:
int[] arr = new int[100];
List<int> list = new List<int> ();
//这里事先存储1-100;
for (int i = 0; i < arr.Length; i++) {
list.Add (i + 1);
}
Random rd = new Random ();
//声明插入的数在数组中的索引
int _Index = 0;
while (list.Count > 0) {
//获取之前存储的集合的随机索引
int num = rd.Next (0, list.Count);
//获取这个数
int temp = list [num];
//将这个数插入数组
arr [_Index] = temp;
_Index++;
//从集合中移除
list.Remove (temp);
}