Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle();
這道題讓我們給數組洗牌,也就是隨機打亂順序,那么由於之前那道題Linked List Random Node我們接觸到了水塘抽樣Reservoir Sampling的思想,這道題實際上這道題也是用類似的思路,我們遍歷數組每個位置,每次都隨機生成一個坐標位置,然后交換當前遍歷位置和隨機生成的坐標位置的數字,這樣如果數組有n個數字,那么我們也隨機交換了n組位置,從而達到了洗牌的目的,這里需要注意的是i + rand() % (res.size() - i)不能寫成rand() % res.size(),雖然也能通過OJ,但是根據這個帖子的最后部分的概率圖表,前面那種寫法不是真正的隨機分布,應該使用Knuth shuffle算法,感謝熱心網友們的留言,參見代碼如下:
class Solution { public: Solution(vector<int> nums): v(nums) {} /** Resets the array to its original configuration and return it. */ vector<int> reset() { return v; } /** Returns a random shuffling of the array. */ vector<int> shuffle() { vector<int> res = v; for (int i = 0; i < res.size(); ++i) { int t = i + rand() % (res.size() - i); swap(res[i], res[t]); } return res; } private: vector<int> v; };
類似題目: