題目:
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算法,該算法原型爲:
該算法將從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;
};