https://leetcode.com/problems/shuffle-an-array/description/
class Solution {
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() {
int N = nums.size();
vector<int> res(nums);
for(int i=0; i<N; i++) {
int j = rand() % (N-i);
swap(res[i], res[i+j]);
}
return res;
}
};
No comments:
Post a Comment