LeetCode #384 Shuffle an Array 数组 洗牌算法

Description


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



思路


使用 rand() % nums.size() 实现数组元素的重排是一个错误的想法,每种排列情况并不是等可能的,最终将导致某些排列结果出现更多,某些排列结果出现更少。
认真学习了洗牌算法 Knuth Shuffle,它使得每种排列情况出现的概率相等。

耗时236ms, ranking 25%

class Solution {
public:
    Solution(const vector<int> &nums) : 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> result = nums;
        
        // knuth-shuffle algorithm
        for (int i = 1; i < result.size(); ++i) {
            int j = rand() % (i + 1);
            swap(result[i], result[j]);
        }
        
        return result;
    }
    
private:
    vector<int> nums;
};



参考


猜你喜欢

转载自www.cnblogs.com/Bw98blogs/p/12670840.html