Sunday, October 22, 2017

[LeetCode]Shuffle an Array

Fisher-Yates算法即可,时间复杂度O(n),常数空间,代码如下:


class Solution {
public:
Solution(vector<int> nums) {
m_nums = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return m_nums;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
int len = m_nums.size();
vector<int> res = m_nums;
for(int i = len - 1; i >= 0; --i)
{
int random = rand() % (i + 1);
swap(res[i], res[random]);
}
return res;
}
private:
vector<int> m_nums;
};
/**
* 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();
*/

No comments:

Post a Comment