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();
Subscribe to see which companies asked this question
代码如下:
1 public class Solution { 2 private int[] origal=null; 3 // private List<Integer> list=new ArrayList<>(); 4 Random random=new Random(); 5 public Solution(int[] nums) { 6 if(nums==null||nums.length==0) origal=nums; 7 origal=nums.clone(); 8 9 } 10 11 /** Resets the array to its original configuration and return it. */ 12 public int[] reset() { 13 if(origal==null||origal.length==0) return origal; 14 return origal.clone(); 15 } 16 17 /** Returns a random shuffling of the array. */ 18 public int[] shuffle() { 19 if(origal==null||origal.length==0) return origal; 20 21 int[] res=new int[origal.length]; 22 res=origal.clone(); 23 24 for(int i=res.length-1;i>0;i--) 25 { 26 try{ 27 int p=random.nextInt(i+1); 28 int temp=res[p]; 29 res[p]=res[i]; 30 res[i]=temp; 31 }catch(ArrayIndexOutOfBoundsException e){} 32 } 33 return res; 34 } 35 } 36 37 /** 38 * Your Solution object will be instantiated and called as such: 39 * Solution obj = new Solution(nums); 40 * int[] param_1 = obj.reset(); 41 * int[] param_2 = obj.shuffle(); 42 */
浙公网安备 33010602011771号