Leetcode 384. 打乱数组
思路:随机数交换法
class Solution {
public:
vector<int> a;
Solution(vector<int>& nums) {
a = nums;
}
vector<int> reset() {
return a;
}
vector<int> shuffle() {
auto b = a;
int n = b.size();
for (int i = 0; i < n; i ++ ) {
swap(b[i], b[i + rand() % (n - i)]);
}
return b;
}
};
/**
* 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();
*/
LeetCode 384:打乱数组:随机交换实现
这篇文章介绍了如何使用随机数交换法解决LeetCode题目384,通过实例展示了如何创建Solution类来维护数组并实现reset和shuffle方法,确保数组元素的随机重新排列。

被折叠的 条评论
为什么被折叠?



