Java: clean and easy to understand solution


  • 0
    E
    public class Solution {
        private int[] numsOriginal;
        private int[] numsShuffled;
        private int size;
        private Random r;
    
        public Solution(int[] nums) {
            // Initialize variables
            numsOriginal = nums;
            numsShuffled = Arrays.copyOf(nums, nums.length);
            size = nums.length;
            r = new Random();
            
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return numsOriginal;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            for (int i = 0; i < size; i++) {
                // Pick an element to swap from the range [i, j)
                int j = r.nextInt(size - i) + i;
                swap(numsShuffled, i, j);
            }
            return numsShuffled;
        }
        
        private void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

Log in to reply
 

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