Shuffle an Array (水塘抽样)

随机性问题

水塘抽样算法可保证每个样本被抽到的概率相等

使用场景:从包含n个项目的集合S中选取k个样本,其中n为一很大或未知的数量,尤其适用于不能把所有n个项目都存放到主内存的情况

Knuth洗牌算法

拿起第i张牌时,只从它前面的牌随机选出j,或从它后面的牌随机选出j交换即可

 1 class Solution {
 2 public:
 3     Solution(vector<int>& nums) {
 4         v = nums;
 5     }
 6     
 7     /** Resets the array to its original configuration and return it. */
 8     vector<int> reset() {
 9         return v;
10     }
11     
12     /** Returns a random shuffling of the array. */
13     vector<int> shuffle() {
14         vector<int> res = v;
15         for (int i = 0; i < res.size(); ++i) {
16             int t = i + rand() % (res.size() - i);
17             swap(res[i], res[t]);
18         }
19         return res;
20     }
21     vector<int> v;
22 };
23 
24 /**
25  * Your Solution object will be instantiated and called as such:
26  * Solution* obj = new Solution(nums);
27  * vector param_1 = obj->reset();
28  * vector param_2 = obj->shuffle();
29  */

 

你可能感兴趣的:(Shuffle an Array (水塘抽样))