【面试题】向一个长度为100的int数组,插入1-100的随机数,不能重复

 1  public int[] GetNoRepeatArrayy(int arrLength)
 2         {
 3             int[] array = new int[arrLength];
 4             IList<int> list = new List<int>();
 5             //准备不重复的数据
 6             for (int i = 0; i < array.Length; i++)
 7             {
 8                 list.Add(i);
 9             }
10             //将不重复的数据随机插入到数组中
11             for (int j = (list.Count - 1); j > -1; j--)
12             {
13                 //获得数据的随机索引
14                 int index = new Random(Guid.NewGuid().GetHashCode()).Next(0, list.Count);
15                 //给数组赋值
16                 array[j] = list[index];
17                 //删除废弃数据,避免重复数据插入到数组中
18                 list.RemoveAt(index);
19             }
20             return array;
21         } 

 

posted @ 2016-02-20 18:04  兴趣就是天赋  阅读(1080)  评论(0)    收藏  举报