打亂一個沒有重複元素的數組。
示例:
// 以數字集合 1, 2 和 3 初始化數組。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打亂數組 [1,2,3] 並返回結果。任何 [1,2,3]的排列返回的概率應該相同。
solution.shuffle();
// 重設數組到它的初始狀態[1,2,3]。
solution.reset();
// 隨機返回數組[1,2,3]打亂後的結果。
solution.shuffle();
關鍵點在於如何打亂一個數組
vector<int> preNums;
Solution(vector<int>& nums) {
preNums = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return preNums;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> res = preNums;
for (int i = 0; i < res.size(); ++i) {
int t = i + rand() % (res.size() - i);
swap(res[i], res[t]);
}
return res;
}