LeetCode刷题实战384:打乱数组
共 2188字,需浏览 5分钟
·
2021-09-22 20:07
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) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果
示例
输入
["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(); // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2]
solution.reset(); // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]
solution.shuffle(); // 随机返回数组 [1, 2, 3] 打乱后的结果。例如,返回 [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;
}
};