All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0301_0400.s0384_shuffle_an_array.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0301_0400.s0384_shuffle_an_array;

// #Medium #Top_Interview_Questions #Array #Math #Randomized #Algorithm_II_Day_20_Others
// #2022_07_13_Time_52_ms_(91.77%)_Space_48.2_MB_(92.20%)

import java.util.Random;

/**
 * 384 - Shuffle an Array\.
 *
 * Medium
 *
 * Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling.
 *
 * 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.
 *
 * **Example 1:**
 *
 * **Input**
 *
 *     ["Solution", "shuffle", "reset", "shuffle"] 
 *     [[[1, 2, 3]], [], [], []]
 *
 * **Output:** 
 *
 *     [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
 *
 * **Explanation:**
 *
 *     Solution solution = new Solution([1, 2, 3]); 
 *     solution.shuffle(); // Shuffle the array [1,2,3] and return its result. 
 *                         // Any permutation of [1,2,3] must be equally likely to be returned. 
 *                         // Example: return [3, 1, 2] 
 *     solution.reset();   // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] 
 *     solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
 *
 * **Constraints:**
 *
 * *   `1 <= nums.length <= 200`
 * *   -106 <= nums[i] <= 106
 * *   All the elements of `nums` are **unique**.
 * *   At most 5 * 104 calls **in total** will be made to `reset` and `shuffle`.
**/
@SuppressWarnings("java:S2245")
public class Solution {
    private int[] nums;
    private Random random;

    public Solution(int[] nums) {
        this.nums = nums;
        this.random = new Random();
    }

    // Resets the array to its original configuration and return it.
    public int[] reset() {
        return this.nums;
    }

    // Returns a random shuffling of the array.
    public int[] shuffle() {
        int[] shuffled = this.nums.clone();
        for (int i = nums.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            swap(shuffled, i, j);
        }
        return shuffled;
    }

    private void swap(int[] shuffled, int i, int j) {
        int tmp = shuffled[i];
        shuffled[i] = shuffled[j];
        shuffled[j] = tmp;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy