关于我的 Leetcode 题目解答,代码前往 Github:https://github.com/chenxiangcyr/leetcode-answers
如何将一个数组 int[] arr
打乱?
利用随机数,进行元素的交换,代码如下:
public int[] shuffle(int[] current) {
// Fisher–Yates Shuffle
for(int i = 1; i < current.length; i++) {
// generate a random number [0, i]
int j = random.nextInt(i + 1);
// swap i and j
int t = current[i];
current[i] = current[j];
current[j] = t;
}
return current;
}