【数组】打乱数组

题目:

解答:

一般来说,对于一个问题我通常会给出两种以上的解法,但是对于洗牌问题,Fisher-Yates洗牌算法即是通俗解法,同时也是渐进最优的解法。

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

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12900108.html