本题其实不算难,其实考点是对API的熟悉,读一读Java的Random Library就会有思路
for (int j = copy.length; j > 0; --j) {int idx = random.nextInt(j);swap(copy, idx, j - 1);}
上面就是核心代码,从后面到前面,一个个random选出,来填充。
另一个难点是验证这个算法的正确性:
- 第一次选,被选中的概率是
- 第二次选,意味这第一次没有被选中,则概率是
- 第三次选,同理,概率是
同理可得,一个数 在 每个位置被选中的概率都是
,所以这个算法是正确的
时间复杂度:
- 空间复杂度不讨论
代码如下:
class Solution {private int[] original;private Random random;public Solution(int[] nums) {original = nums.clone();random = new Random();}/** Resets the array to its original configuration and return it. */public int[] reset() {return original;}/** Returns a random shuffling of the array. */public int[] shuffle() {int[] copy = original.clone();for (int j = copy.length; j > 0; --j) {int idx = random.nextInt(j);swap(copy, idx, j - 1);}return copy;}private void swap(int[] array, int i, int j) {int tmp = array[i];array[i] = array[j];array[j] = tmp;}}/*** 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();*/
