目的: 洗牌后, 每张牌出现在每个位置上的概率是相同的
相同问题:
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)
&#x