题目:
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();
思路:看到题目立刻就能想到STL中的random_shuffle算法,该算法原型为:
voidrandom_shuffle(RandomAccessIteratorfirst,RandomAccessIteratorlast)
该算法将从N!种可能的数组排列序列中选择一种,《The Art of Computer Programming 》3.4.2节给出了关于随机排列的算法。假设需要随机排列的序列为X1,X2,……,Xt,算法描述如下:
- 初始化 ,另j = t
- 生成0~1之间均匀分布的随机数U
- 另 k = j*U + 1(向下取整,k相当于1~j之间均匀分布的随机整数),交换Xj和Xk
j = j - 1,如果j > 1,goto步骤2
C++代码描述如下:
random_shuffule(RandomAccessIterator first,RandomAccessIterator last){
if(first == last)return;
for(auto iter = first + 1;iter!=last;++iter)
iter_swap(i,first + rand((i - first ) + 1));
}
解答时可直接使用STL算法:
class Solution {
public:
Solution(vector<int> nums):data(nums) {
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return data;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> res = data;
random_shuffle(res.begin(),res.end());
return res;
}
vector<int> data;
};