Share my simple Java solution, beat 79.20%.


  • 0
    G

    The shuffling process is to create permutations (the problem of Mississippi), so we used the swap() idea which learned from our Algorithms class.

    public class Solution {
    	private int[] original;
    	private int[] shuffled;
    	private int length;
        public Solution(int[] nums) {
            length = nums.length;
            original = Arrays.copyOf(nums, nums.length);
            shuffled = Arrays.copyOf(nums, nums.length);
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return original;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
        	//using swap?
        	Random rand = new Random();
        	for(int i=0; i<length; i++){
                int index2 = rand.nextInt(length-i)+i;
                swap(i,index2,shuffled);
        	}
        	return shuffled;
        }
        
        private void swap(int index1, int index2, int[] res){
        	int tp = res[index1];
        	res[index1] = res[index2];
        	res[index2] = tp;
        }    
    }

Log in to reply
 

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