LeetCode No.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();

===================================================================

題目鏈接:https://leetcode.com/problems/shuffle-an-array/

題目大意:洗牌和復原操作,要求洗牌得到結果等概率出現。

思路:主要是洗牌操作,隨機生成一個位置跟最後一位交換,再隨機生成一個位置跟倒數第二位交換,交換操作保證集合的正確性。

參考代碼:

class Solution {
public:
    Solution(vector<int> nums) {
        this -> nums = nums ;
        srand ( time ( 0 ) ) ;
    }
    
    /** 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> ans = nums ;
        for ( int i = ans.size() - 1 ; i > 0 ; i -- )
            swap ( ans[i] , ans[rand() % ( i + 1 )] ) ;
        return ans ;
    }
private:
    vector <int> nums ;
};

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章