Fisher-Yates shuffle C++ solution


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.