微软面试题: LeetCode 384. 打乱数组 出现次数:3

题目描述:

给定一个无重复元素的整数数组,每次等概率随机返回 n ! 中的一个 。

代码如下:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 class Solution {
 4 public:
 5     Solution(vector<int>& nums) {
 6         m_nums = nums;
 7     }
 8     
 9     /** Resets the array to its original configuration and return it. */
10     vector<int> reset() {
11         return m_nums;
12     }
13     
14     /** Returns a random shuffling of the array. */
15     vector<int> shuffle()
16     {
17         vector<int> shuffle_nums(m_nums);
18         for(int i = 0; i < shuffle_nums.size();++i)
19         {
20            // rand()能随机生成0到最大随机数的任意整数
21            //rand() % (i + 1)能随机生成0到i中的任意整数
22             std::swap(shuffle_nums[i],shuffle_nums[random() % (i + 1)]);
23         } 
24         return shuffle_nums;
25     }
26      
27 private:
28     vector<int> m_nums;
29 };

在开发中遇到这个需求,可以直接使用  std::random_shuffle(nums.begin(),nums.end());

原文地址:https://www.cnblogs.com/wangxf2019/p/14601624.html