题目来源
要求将一个数组随机打乱。
不会…
看了下答案,需要用到随机洗牌算法,介绍可以看这里。
只需要从后往前遍历,每次随机从i中取一个数,放到后面。没有看具体怎么证明…现在就记住这样子是可以的吧…
代码如下:
class Solution {
public:
Solution(vector<int> nums) {
this->nums = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return nums;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> res(nums);
int n = res.size();
for (int i=n-1; i>=0; i--) {
int pos = rand() % (i + 1);
swap(nums[pos], nums[i]);
}
return res;
}
private:
vector<int> nums;
};
/**
* 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();
*/
网友评论