Shuffle an Array - Medium - L

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/shuffle-an-array/

Given an integer array nums, design an algorithm to randomly shuffle the array.

Implement the Solution class:

Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling of the array.

Approach

  • Arrays

Solution

``` class Solution { public: vector orig;

Solution(vector<int>& nums) {
    orig=nums;
}

/** Resets the array to its original configuration and return it. */
vector<int> reset() {
    return orig;
}

/** Returns a random shuffling of the array. */
vector<int> shuffle() {
    vector<int> ans=orig;
    vector<int> fin;
    for(int i=0;i<orig.size();i++){
        int val=(rand()%(ans.size()));
        fin.push_back(ans[val]);
        ans.erase(ans.begin()+val);
    }
    return fin;
} };

/**

  • Your Solution object will be instantiated and called as such:
  • Solution* obj = new Solution(nums);
  • vector param_1 = obj->reset();
  • vector param_2 = obj->shuffle(); */