题目[leetcode链接]
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
思路:
随机洗牌问题
从头开始遍历,每次在[0,len)之间产生一个随机数,交换遍历到的位置与随机数位置上的数。
具体代码实现:
public class Solution {
int[] nums;
int[] result;
public Solution(int[] nums) {
int len = nums.length;
this.nums = new int[len];
result = new int[len];
for (int i = 0; i < len; i++) {
this.nums[i] = nums[i];
result[i] = nums[i];
}
}
/* 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 nums_len = nums.length;
Random random = new Random();
for (int i = 0; i < nums_len; i++) {
int r = random.nextInt(nums_len);
int temp = result[i];
result[i] = result[r];
result[r] = temp;
}
return result;
}
}
需要注意的问题:
返回值result的创建不能在shuffle()函数中创建,这样每次shuffle都会新创建空间,浪费很多空间,应该如代码中写的 在类中创建一个成员变量,每次用都用这个就可以。