"随机产生不重复的N个数字"在笔试中这类题目出现的概率很高,一般可以使用如下算法解答:
int n = 20; IList<int> nums = new List<int>(); while (nums.Count < n) { int number = new Random().Next(n); if (!nums.Contains(number)) { nums.Add(number); } }
上述方法无法确认其时间复杂度,可以通过"交换位置"的方法,提高效率,算法如下:
int[] numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; int n = numbers.Length; IList<int> nums = new List<int>(); int i = 1; while (nums.Count < n) { int idx = new Random().Next(n - i); int number = numbers[idx]; nums.Add(number); numbers[idx] = numbers[n - i]; i++; }
通过dotTrace分析两者的性能差异,先上代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { GetMethod1(1000); GetMethod2(1000); } private static IList<int> GetMethod1(int n) { IList<int> nums = new List<int>(); while (nums.Count < n) { int number = new Random().Next(n); if (!nums.Contains(number)) { nums.Add(number); } } return nums; } private static IList<int> GetMethod2(int n) { var numbers = new int[n]; for (int j = 0; j < n; j++) { numbers[j] = j; } IList<int> nums = new List<int>(); int i = 1; while (nums.Count < n) { int idx = new Random().Next(n - i); int number = numbers[idx]; nums.Add(number); numbers[idx] = numbers[n - i]; i++; } return nums; } } }
dotTrace分析结果: