LeetCode#384配列をシャッフルする

説明文


重複せずに一連の数値をシャッフルします。

例:

// 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、ランキング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;
};



参考資料


  • 「Knuthシャッフルアルゴリズムをシャッフルするための正しい姿勢」:https ://yjk94.wordpress.com/2017/03/17/shuffling-knuth-shuffleアルゴリズムの正しい姿勢/
  • 「[LeetCode]配列の配列をシャッフルする」:https ://www.cnblogs.com/grandyang/p/5783392.html


おすすめ

転載: www.cnblogs.com/Bw98blogs/p/12670840.html