题目链接:384. 打乱数组
2020.10.14第一次解答:
解题思路
暴力破解法:(洗牌不会)
在Solution内增加成员vector<int> nums,用于保存原始数组
对于reset()函数,直接返回保存的原始数组
对于shuffle()函数,复制一个原始数组,使用rand()随机将元素复制到结果数组中
C++代码
class Solution {
private:
vector<int> nums;
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() {
//srand(time(0)); 依题意,不可以使用srand()
vector<int> v(nums);
vector<int> ans;
while (!v.empty()) {
int pivot = rand() % v.size();
ans.emplace_back(v[pivot]);
v.erase(begin(v) + pivot, begin(v) + pivot + 1);
}
return ans;
}
};
/**
* 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();
*/

本文介绍了如何使用C++实现一个Solution类,通过暴力破解法和洗牌算法重置和随机打乱输入的整数数组。讲解了reset()和shuffle()函数的具体实现,以及在不使用`srand()`的情况下如何生成随机元素。
464

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



