Shuffle an Array

题目来源
要求将一个数组随机打乱。
不会…
看了下答案,需要用到随机洗牌算法,介绍可以看这里。
只需要从后往前遍历,每次随机从i中取一个数,放到后面。没有看具体怎么证明…现在就记住这样子是可以的吧…
代码如下:

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

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * vector param_1 = obj.reset();
 * vector param_2 = obj.shuffle();
 */

你可能感兴趣的:(Shuffle an Array)