384. 打乱数组
题目描述
打乱一个没有重复元素的数组。
示例:
// 以数字集合 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();
实现
shuffle方法使用Random类的nextInt方法获取随机数
class Solution {
int[] origin;
int[] cur;
public Solution(int[] nums) {
origin = nums;
cur = new int[nums.length];
for(int i=0; i<nums.length; i++) {
cur[i] = nums[i];
}
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
for(int i=0; i<origin.length; i++) {
cur[i] = origin[i];
}
return cur;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int len = cur.length;
Random r = new Random();
for(int i=0; i<len; i++) {
int in = r.nextInt(len - i) + i; //插入到i位置的数据的索引
int temp = cur[i];
cur[i] = cur[in];
cur[in] = temp;
}
return cur;
}
}
/**
* 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();
*/
- 时间复杂度:O(n)
- 空间复杂度:O(n)
本文详细解析了如何使用Random类的nextInt方法实现打乱数组的功能,通过实例演示了初始化、重置及随机打乱数组的过程,介绍了Solution类的实现细节。
433

被折叠的 条评论
为什么被折叠?



