Randomness
Reservoir sampling algorithm ensures that each sample is pumped equal probability
Where k samples selected from the set S of n items comprising, where n is a number of large or unknown, especially for not all the n items are stored to the main memory: a scene using
Knuth shuffle algorithm
Pick up the first i
time cards, which were randomly selected from the front of the cardj,或从它后面的牌随机选出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<int> param_1 = obj->reset(); 28 * vector<int> param_2 = obj->shuffle(); 29 */