删除损性能,以替换方法取之


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
数组:0 1 2 3 4 5
取数据:
方法1:取出一个删除一个,但删除很费时,性能并不高
方法2:取出一个,用数组最后一位填充,相当于将最后一位前移,同时将最后一排除在下次取数据之外即可。
<a href="http://www.cnblogs.com/eaglet/archive/2011/01/17/1937083.html">不重复随机数列生成算法</a>

新方法:

下面的时间复杂度很小
public static int[] GetRandomSequence2(int total)

{

int[] sequence = new int[total];

int[] output = new int[total];

for (int i = 0; i < total; i++)

{

sequence[i] = i;

}

Random random = new Random();

int end = total - 1;

for (int i = 0; i < total; i++)

{

int num = random.Next(0, end + 1);

output[i] = sequence[num];

sequence[num] = sequence[end];

end--;  //缩小范围,将最后一位前移,并排除最后一位。

}

return output;

}

老方法:时间复杂度为n2
public static int[] GetRandomSequence0(int total)

{

int[] hashtable = new int[total];

int[] output = new int[total];

Random random = new Random();

for (int i = 0; i < total; i++)

{

int num = random.Next(0, total);

while (hashtable[num] > 0)

{

num = random.Next(0, total);

}

output[i] = num;

hashtable[num] = 1;

}

return output;

}