Java solution using knuth shuffle


  • 1
    public class Solution {
        private int[] origin = null;
        
        public Solution(int[] nums) {
            if (nums == null || nums.length == 0) origin = nums;
            origin = nums.clone();
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            if (origin == null || origin.length == 0) return origin;
            return origin.clone();
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            if (origin == null || origin.length == 0) return origin;
            
            Random rand = new Random();
            int[] a = origin.clone();
            int j = 0;
            
            for (int i = a.length-1; i >= 0; i--) {
                j = rand.nextInt(i+1);
                exchange(a, i, j);
            }
            return a;
        }
        
        private void exchange(int[] a, int i, int j) {
            int tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
    }

Log in to reply
 

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