题目分析
原题链接,登录 LeetCode 后可用
这道题目要求我们完善 shuffle 方法,将一个数组进行乱序操作,同时要求我们完善 reset 方法,这个方法能够返回原数组。
代码
class Solution {
private int[] nums;
private int[] res;
private Random random;
public Solution(int[] nums) {
this.nums = nums;
res = Arrays.copyOf(nums, nums.length);
random = new Random();
}
/** 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() {
if(res == null) {
return null;
} else {
for(int i = 1; i < res.length; i++) {
// 从 0 ~ i 下标中任选一个位置和当前位置的值进行交换
int j = random.nextInt(i + 1);
swap(res, i, j);
}
return res;
}
}
private void swap(int[] res, int i, int j) {
int temp = res[i];
res[i] = res[j];
res[j] = temp;
}
}
/**
* 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();
*/
网友评论