Straight forward Java Solution


  • 0

    My steps of shuffle:

    1. Create a new array with the same size of original array
    2. Randomly put number from original array to the new array

    I'm using a boolean[] visited array to avoid choosing the same number more than once. In this way, every number in original array will be selected and put into new array once.

    public class Solution {
        public int[] ini;
        public Random rand;
        
        public Solution(int[] nums) {
            ini = nums;
            rand = new Random();
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return ini;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            boolean[] visited = new boolean[ini.length];
            int[] nums = new int[ini.length];
            int index = 0;
            while (index < nums.length) {
                int r = rand.nextInt(nums.length);
                if (visited[r] == false) {
                    nums[index++] = ini[r];
                    visited[r] = true;
                }
            }
            return nums;
        }
    }
    

Log in to reply
 

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