Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle();
Solution:
1 public class Solution { 2 int[] numArr; 3 4 public Solution(int[] nums) { 5 numArr = new int[nums.length]; 6 for (int i=0;i<nums.length;i++){ 7 numArr[i] = nums[i]; 8 } 9 } 10 11 /** Resets the array to its original configuration and return it. */ 12 public int[] reset() { 13 return numArr; 14 } 15 16 /** Returns a random shuffling of the array. */ 17 public int[] shuffle() { 18 int[] randArr = new int[numArr.length]; 19 for (int i=0;i<numArr.length;i++) randArr[i] = numArr[i]; 20 int last = numArr.length-1; 21 Random engine = new Random(); 22 while (last>=0){ 23 int target = engine.nextInt(last+1); 24 int temp = randArr[last]; 25 randArr[last] = randArr[target]; 26 randArr[target] = temp; 27 last--; 28 } 29 return randArr; 30 } 31 } 32 33 /** 34 * Your Solution object will be instantiated and called as such: 35 * Solution obj = new Solution(nums); 36 * int[] param_1 = obj.reset(); 37 * int[] param_2 = obj.shuffle(); 38 */