目的: 洗牌后, 每张牌出现在每个位置上的概率是相同的
相同问题:
1.shuffle a deck of cards(洗牌)
2.randomize an array(打散数组)
3.generate a random permutation of array elements(随机排列数组)
最佳算法(1和2是完全相同的算法的两种做法):
从头或者从尾遍历数组, 把当前元素和剩余元素中一个随机元素交换。 重复此操作一直到遍历完成。
- Start from the first element. Swap it with a random choose element in the whole array(including itself). Now consider the array is from 1 to N-1. Repeat the proccess until you hit the last element.
- Start from the last element. Swap it with a random choosen element in the whole array(including itself). Now consider the array is from 0 to N-2. Repeat the proccess until you hit the first element.
复杂度:
Space: O(1)
Time: O(n)
c++ 代码:
/* 1. start from the first element*/
void shuffle(int card[], int n)
{
// Initial

本文探讨了如何实现随机洗牌算法,适用于洗牌、打散数组和生成数组随机排列等场景。最佳算法是从数组首尾开始,将当前元素与剩余元素中的随机元素进行交换,直至遍历完成。算法的空间复杂度为O(1),时间复杂度为O(n)。文章还提供了C++代码示例,强调了不同随机选择方式的注意点。
最低0.47元/天 解锁文章
1229

被折叠的 条评论
为什么被折叠?



