題目來源
要求將一個數(shù)組隨機打亂。
不會…
看了下答案雄妥,需要用到隨機洗牌算法,介紹可以看這里依溯。
只需要從后往前遍歷老厌,每次隨機從i中取一個數(shù),放到后面黎炉。沒有看具體怎么證明…現(xiàn)在就記住這樣子是可以的吧…
代碼如下:
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();
*/