Java solution using 2 arrays.


  • 0
    Q

    We can just keep original array and simply return it on reset.

    public class Solution {
       int[] original,shuffled;
       Random rnd = new Random();
       public Solution(int[] nums){
          original = nums;
          shuffled = original.clone();
       }
       public int[] shuffle(){
          for (int i=shuffled.length-1; i>=1; i--){
             int tmp = shuffled[i];
             int rand = rnd.nextInt(i+1);
             shuffled[i] = shuffled[rand];
             shuffled[rand] = tmp;
          }
          return shuffled;
       }
       public int[] reset() {
          return original;
       }
    }
    

  • 0
    F

    I have basically the same idea. Store one original array and one "shuffled array". Use Fisher-Yates shuffle.

    public class Solution {
        private int[] origNums;
        private int[] randNums;
        public Solution(int[] nums) {
            origNums = Arrays.copyOf(nums, nums.length);
            randNums = Arrays.copyOf(nums, nums.length);
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return origNums;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            Random rand = new Random();
            int range = randNums.length;
            while (range > 0) {
                int pos = rand.nextInt(range);
                int tmp = randNums[pos];
                randNums[pos] = randNums[range - 1];
                randNums[range - 1] = tmp;
                --range;
            }
            return randNums;
        }
    }
    

Log in to reply
 

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