[Leetcode] 384. Shuffle an Array 解题报告

题目

Shuffle a set of numbers without duplicates.

Example:

// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();

思路

这是洗牌的一种高效的标准方法:遍历每一个元素,并且随机选择一个从它开始的位置,与这个位置交换。可以证明任意一个元素随机到任意一个位置的概率都是1/n。怎么证明呢?用数学归纳法:

1)当只有一个元素的时候,显然满足条件(为了保险,可以验证当有两个元素的时候也满足条件);

2)假设当有n个元素的时候满足条件(n >= 1),那么当有n+1个元素的时候呢?第一个元素显然有1/(n+1)的概率被留在第一位,有n/(n+1)的概率和后面的元素发生交换。假设和第m个元素发生了交换, 而由于2 <= m <= n+1,所以第m个元素被调换到第一个位置的概率都是1/(n+1)。那么从第二个位置到最后一个位置上的情况呢?根据归纳假设,这n个元素留在每个位置上的概率都是1/n,又由于有n/(n+1)的概率发生这种情况,所以每个元素留在每个位置上的概率都是1/n * n/(n+1) = 1/(n+1)。

该算法的时间复杂度是O(n),空间复杂度也是O(n)。


代码

class Solution {
public:
    Solution(vector<int> nums) {
        vec = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return vec;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        if (vec.size() == 0) {
            return {};
        }
        vector<int> tem(vec);
        int len = vec.size();
        for (int i = 0; i < len; ++i) {
            int pos = rand() % (len - i);
            swap(tem[i], tem[i + pos]);     // swap i-th and the one randomly selected behind it
        }
        return tem;
    }
private:
    vector<int> vec;
};

/**
 * 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();
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值