Java Solution using Random


  • 0
    H
    import java.util.Random;
    class Solution {
    
    	private int[] nums;
    	private int n;
    	private Random rand;
    
    	public Solution(int[] nums) {
    		this.nums = nums;
    		this.n = this.nums.length;
    		this.rand = new Random();
    	}
    
    	/** Resets the array to its original configuration and return it. */
    	public int[] reset() {
    		return this.nums;
    	}
    
    	/** Returns a random shuffling of the array. */
    	public int[] shuffle() {
    		int[] shuffled = this.nums.clone();
    		for (int i = 0; i < this.n; ++i) {
    			int k = rand.nextInt(i + 1);
    			swap(shuffled, i, k);
    		}
    		return shuffled;
    	}
    	
    	public void swap(int[] arr, int a, int b) {
    		int t = arr[a];
    		arr[a] = arr[b];
    		arr[b] = t;
    	}
    }

Log in to reply
 

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