[LeetCode]384. Shuffle an Array
题目描述
思路
洗牌算法
逆序遍历数组,对于当前位置的数,随机生成一个0-当前位置的表示位置的数,交换二者
代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
Solution(vector<int> nums) {
len = nums.size();
this->nums.resize(len);
source.resize(len);
if (len) {
memcpy(&this->nums[0], &nums[0], len * sizeof(int));
memcpy(&source[0], &nums[0], len * sizeof(int));
}
}
vector<int> reset() {
return source;
}
vector<int> shuffle() {
for (int i = len - 1; i >= 0; i--) {
swap(nums[i], nums[rand() % (i + 1)]);
}
return nums;
}
private:
vector<int> nums;
vector<int> source;
int len;
};
int main() {
vector<int> nums = {1, 2, 3, 4, 6, 9};
Solution s(nums);
vector<int> random = s.shuffle();
vector<int> source = s.reset();
cout << "nums:" << endl;
for (auto p : nums) {
cout << p << " ";
}
cout << endl;
cout << "random:" << endl;
for (auto p : random) {
cout << p << " ";
}
cout << endl;
cout << "source:" << endl;
for (auto p : source) {
cout << p << " ";
}
cout << endl;
system("pause");
return 0;
}