384. Shuffle an Array
遍历原数组,当前I,然后随机nextInt(length-i),两个SWAP,就表示随便选了一个放到I了,然后再看I+1,I+2。。到最后就行了。
int[] origin;
int[] res;
Random rdm = new Random();
public Solution(int[] nums)
{
origin = nums;
res = Arrays.copyOf(nums,nums.length);
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return origin;
}
/** Returns a random shuffling of the array. */
public int[] shuffle()
{
int length = origin.length;
if(length == 0) return res;
for(int m = 0 ; m < origin.length;m++)
{
int rdmI = rdm.nextInt(length-m);
swap(res,m,rdmI);
}
return res;
}
public void swap(int[] res, int m, int rdmI)
{
int temp = res[m];
res[m] = res[rdmI];
res[rdmI] = temp;
}