题目描述:
打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
思路:这里我直接调用Collections的shuffle方法,进行调用
感觉没啥技术含量。。。
class Solution {
int solution[] = null;
int solution2[] = null;
public Solution(int[] nums) {
solution = nums;
solution2 = new int[nums.length];
int index = 0;
for (int i : nums) {
solution2[index++] = i;
}
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return solution2;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
List<Integer> tem = new ArrayList<>();
for (Integer integer : solution) {
tem.add(integer);
}
Collections.shuffle(tem);
int index = 0;
for (Integer integer : tem) {
solution[index++] = integer;
}
return solution;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/
参考别人手动实现的
class Solution {
private int[] source;
public Solution(int[] nums) {
source = Arrays.copyOf(nums, nums.length);
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return Arrays.copyOf(source, source.length);
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] target = Arrays.copyOf(source, source.length);
int length = target.length;
for (int i = length - 1; i > 0; i--) {
// 随机[0-i]选一个数放在末尾,然后末尾依次减小,可以是自身i所以nextInt中是i+1
int randomIndex = new Random().nextInt(i+1);
int temp = target[i];
target[i] = target[randomIndex];
target[randomIndex] = temp;
}
return target;
}
}
参考官网的解释,使用洗牌算法
添加链接描述