?LeetCode刷題實(shí)戰(zhàn)384:打亂數(shù)組
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Solution(int[] nums) 使用整數(shù)數(shù)組 nums 初始化對(duì)象
int[] reset() 重設(shè)數(shù)組到它的初始狀態(tài)并返回
int[] shuffle() 返回?cái)?shù)組隨機(jī)打亂后的結(jié)果
示例
輸入
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
輸出
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
解釋
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // 打亂數(shù)組 [1,2,3] 并返回結(jié)果。任何 [1,2,3]的排列返回的概率應(yīng)該相同。例如,返回 [3, 1, 2]
solution.reset(); // 重設(shè)數(shù)組到它的初始狀態(tài) [1, 2, 3] 。返回 [1, 2, 3]
solution.shuffle(); // 隨機(jī)返回?cái)?shù)組 [1, 2, 3] 打亂后的結(jié)果。例如,返回 [1, 3, 2]
解題
class Solution {
vector<int> origin;
vector<int> ans;
public:
Solution(vector<int>& nums) {
origin = ans = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return origin;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
int n = origin.size(),i;
for(i = 0; i < n; ++i)
swap(ans[i], ans[rand()%n]);
return ans;
}
};
