【LeetCode-数学】打乱数组

题目描述

打乱一个没有重复元素的数组。
示例:

// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();

// 重设数组到它的初始状态[1,2,3]。
solution.reset();

// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();

题目链接: https://leetcode-cn.com/problems/shuffle-an-array/

思路

重设到初始状态比较好做,只需要再使用一个数组 copy 保存原来的数组 nums,重设的时候将 nums 设为 copy 即可。

打乱可以使用 Fisher-Yates 洗牌算法,也就是遍历 nums,假设当前的下标为 i,则生成一个 [i, nums.size()-1] 之间的随机数 idx,swap(nums[i], nums[idx]) 即可。代码如下:

class Solution {
    vector<int> nums;
    vector<int> copy;
public:
    Solution(vector<int>& nums) {
        this->nums = nums;
        this->copy = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        nums = copy;
        return nums;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        for(int i=0; i<nums.size(); i++){
            int idx = rand()%nums.size();
            swap(nums[i], nums[idx]);
        }
        return 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();
 */
原文地址:https://www.cnblogs.com/flix/p/13283040.html