Shuffle an Array
给一个数组, 返回它的随机洗牌. 直接用random就好, 一般o(n)的复杂度都可以.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class Solution { int[] nums; private Random random; public Solution(int[] nums) { this.nums = nums; random = new Random(System.currentTimeMillis()); } /** Resets the array to its original configuration and return it. */ public int[] reset() { return nums; } /** Returns a random shuffling of the array. */ public int[] shuffle() { int[] ary = nums.clone(); for(int i = 1 ; i < ary.length; i++){ int index = random.nextInt(i+1); swap(ary, i, index); } return ary; } public void swap(int[] ary, int i, int j){ int t = ary[i]; ary[i] = ary[j]; ary[j] = t; } } /** * 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(); */ |