Given an array of integers (without any duplicates), shuffle the array such that all permutations are equally likely to be generated.
Solution: 从大到小,每次在[0, i]中随机产生一个index,再swap(array, index, i)
产生[0, x) int的方法:Math.random().nextInt(x)或(int)(Math.random() * x)
public void shuffle(int[] array) {
if (array.length < 2) {
return;
}
Random rand = new Random();
for (int i = array.length - 1; i >= 1; i--) {
int index = rand.nextInt(i + 1);
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}