384. Shuffle an Array

2020-12-04 00:29发布

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();


洗牌算法

假如是1 2 3 4 5 6 7 8

0-7位置上的某个数 跟 位置7上的数互换
0-6位置上的某个数 跟  位置6上的数互换
0-5位置上的某个数 跟  位置5上的数互换
。。。
0-0位置上的某个数 跟  位置0上的数互换



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

 

 

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

 

 
标签: