思路,这里用到了java中的Random类。第一个初始化的和第二个返回初始状态的函数很好写,只初始化nums和返回nums即可。第三个函数,先克隆一个nums数组s,然后取[0,s.length)之间的随机数temp作为索引,把nums[temp]的值依次赋给s[],同时用一个boolean数组b判断这个索引有没有重复取。最后返回s。这里没有使用swap 。代码:
class Solution {
private int [] nums;
private Random random;
public Solution(int[] nums) {
this.nums = nums;
random = new Random();
}
public int[] reset() {
return nums;
}
public int[] shuffle() {
int [] s = new int [nums.length];
boolean [] b = new boolean [nums.length];
for (int i = 0; i < s.length; i++) {
int temp = random.nextInt(s.length);
while (b[temp]) {
temp = random.nextInt(s.length);
}
b[temp] = true;
s[i] = nums[temp];
}
return s;
}
}
/**
* 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();
*/