【LeetCode & 剑指offer刷题】发散思维题9:Shuffle an Array
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
Shuffle an Array
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();
//方法:洗牌算法 Fisher–Yates shuffle algorithm
//O(n),O(n)
#include <cstdlib>
#include <algorithm>
class Solution
{
private:
vector<int> original; //定义成员变量
vector<int> array;
public:
Solution(vector<int> nums) //?这里为什么不用引用
{
srand(time(nullptr)); // 以当前时间为随机生成器的种子,这里要加,不加速度很慢(猜想可前没能是如果rand()之有srand,则每次都会运行srand(1)比较耗时)
original = nums; //这里为深拷贝
array = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset()
{
return original;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle()
{
int i,j;
for( i = array.size()-1; i>0; i--) //从后往前扫描
{
j = rand() % (i+1); //产生0~i的随机数(!!注意要产生0~i的随机数,而不是0~i-1,因为要包换不交换的情况)
swap(array[i], array[j]); //用当前数与随机选择的数进行交换
}
return array;
}
};
/*方法二:用stl中shuffle函数,如shuffle(v.begin(), v.end());
实现说明:rand() % (i+1) 实际上不准确,因为生成的数对于多数 i 值不均匀分布。正确实现将实际上需要重新实现 C++11 std::uniform_distributtion
*/
/**
* 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();
*/