Shuffle an Array
给一个数组, 返回它的随机洗牌. 直接用random就好, 一般o(n)的复杂度都可以.
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();
*/