384. Shuffle an Array
最直观的,直接新建复制数组,i
的取值范围:0 到 (size - 1)
,随机数random
的位置:i后面的所有index
,然后交换i
和random
的位置。
class Solution {
int[] nums;
int size;
Random random;
public Solution(int[] nums) {
this.nums = nums;
this.size = nums.length;
this.random = new Random();
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return this.nums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] copy = Arrays.copyOf(this.nums, this.size);
for (int i = 0; i < this.size - 1; i++) {
int randomIndex = (int) this.random.nextInt(this.size - i) + i;
int tmp = copy[i];
copy[i] = copy[randomIndex];
copy[randomIndex] = tmp;
}
return copy;
}
}