初級算法之設計問題:shuffle an array

打亂一個沒有重複元素的數組。

示例:

// 以數字集合 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();

關鍵點在於如何打亂一個數組

    vector<int> preNums;
    Solution(vector<int>& nums) {
        preNums = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return preNums;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
         vector<int> res = preNums;
        for (int i = 0; i < res.size(); ++i) {
            int t = i + rand() % (res.size() - i);
            swap(res[i], res[t]);
        }
        return res;
    }
發佈了44 篇原創文章 · 獲贊 0 · 訪問量 1294
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章