使用Fisher-Yates 洗牌算法实现random_shuffle函数
Posted Harris-H
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Fisher-Yates 洗牌算法实现random_shuffle函数相关的知识,希望对你有一定的参考价值。
使用Fisher-Yates 洗牌算法实现random_shuffle函数
class Solution
public:
Solution(vector<int>& nums)
this->nums = nums;
this->original.resize(nums.size());
copy(nums.begin(), nums.end(), original.begin());
vector<int> reset()
copy(original.begin(), original.end(), nums.begin());
return nums;
vector<int> shuffle()
for (int i = 0; i < nums.size(); ++i)
int j = i + rand() % (nums.size() - i);
swap(nums[i], nums[j]);
return nums;
private:
vector<int> nums;
vector<int> original;
;
直接调用random_suffle 函数实现
class Solution
public:
vector<int> b;
Solution(vector<int>& a)
b=a;
vector<int> reset()
return b;
vector<int> shuffle()
vector<int> c = b;
random_shuffle(c.begin(),c.end());
return c;
;
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* vector<int> param_1 = obj->reset();
* vector<int> param_2 = obj->shuffle();
*/
以上是关于使用Fisher-Yates 洗牌算法实现random_shuffle函数的主要内容,如果未能解决你的问题,请参考以下文章