码迷,mamicode.com
首页 > 其他好文 > 详细

384. Shuffle an Array

时间:2018-03-18 17:21:21      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:info   pos   img   turned   conf   alt   iat   result   and   

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


洗牌算法

技术分享图片

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  */

 

 

384. Shuffle an Array

标签:info   pos   img   turned   conf   alt   iat   result   and   

原文地址:https://www.cnblogs.com/mengchunchen/p/8596006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!