Shuffle an Array

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

class Solution {
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() {
        vector<int> 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<int> 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();
 */
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容