Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Implement the Solution class:
Solution(int[] nums) Initializes the object with the integer array nums.
int[] reset() Resets the array to its original configuration and returns it.
int[] shuffle() Returns a random shuffling of the array.
classSolution { int[] data; int[] shuffle; Random r; publicSolution(int[] nums) { data = nums; shuffle = newint[nums.length]; r = newRandom(); for(inti=0; i < data.length; i++){ shuffle[i] = nums[i]; } } publicint[] reset() { return data; } publicint[] shuffle() { for(inti= data.length-1 ; i >= 0; i--){ swap(i, r.nextInt(i+1)); } return shuffle; } privatevoidswap(int i, int j){ inttemp= shuffle[i]; shuffle[i] = shuffle[j]; shuffle[j] = temp; } }
/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int[] param_1 = obj.reset(); * int[] param_2 = obj.shuffle(); */
classSolution { int[] data; Random r; publicSolution(int[] nums) { data = nums; r = newRandom(); } publicint[] reset() { return data; } publicint[] shuffle() { ArrayList<Integer> bin = newArrayList<>(); for(inti=0; i < data.length; i++){ bin.add(data[i]); } int[] ret = newint[data.length]; for(inti=0 ; i < data.length; i++){ intrandom= r.nextInt(bin.size()); ret[i] = bin.get(random); bin.remove(random); } return ret; } }
/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int[] param_1 = obj.reset(); * int[] param_2 = obj.shuffle(); */