[LeetCode] 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();

 

這道題讓我們給數組洗牌,也就是隨機打亂順序,那么由於之前那道題Linked List Random Node我們接觸到了水塘抽樣Reservoir Sampling的思想,這道題實際上這道題也是用類似的思路,我們遍歷數組每個位置,每次都隨機生成一個坐標位置,然后交換當前遍歷位置和隨機生成的坐標位置的數字,這樣如果數組有n個數字,那么我們也隨機交換了n組位置,從而達到了洗牌的目的,這里需要注意的是i + rand() % (res.size() - i)不能寫成rand() % res.size(),雖然也能通過OJ,但是根據這個帖子的最后部分的概率圖表,前面那種寫法不是真正的隨機分布,應該使用Knuth shuffle算法,感謝熱心網友們的留言,參見代碼如下:

 

class Solution {
public:
    Solution(vector<int> nums): v(nums) {}
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return v;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        vector<int> res = v;
        for (int i = 0; i < res.size(); ++i) {
            int t = i + rand() % (res.size() - i);
            swap(res[i], res[t]);
        }
        return res;
    }
    
private:
    vector<int> v;
};

 

類似題目:

Linked List Random Node

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM