Shuffle a set of numbers without duplicates.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
// 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(); |
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Author: Huahua // Running time: 249 ms class Solution { public: Solution(vector<int> nums) { nums_ = std::move(nums); } /** Resets the array to its original configuration and return it. */ vector<int> reset() { return nums_; } /** Returns a random shuffling of the array. */ vector<int> shuffle() { vector<int> output(nums_); const int n = nums_.size(); for (int i = 0; i < n - 1; ++i) { int j = rand() % (n - i) + i; std::swap(output[i], output[j]); } return output; } private: vector<int> nums_; }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment