Middle
一开始很naive地觉得这道题就是考backtracking, 找到所有的permutations然后返回任意一个.然而闪亮亮的TLE,说明这道题不是想考你这个. 注意一下`r.nextInt(i + 1)'这个方法返回的是[0, i]中的任意一个int. 要返回[min, max]中的任意一个int, 可以用以下方法:
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
Fisher–Yates shuffle Algorithm
class Solution {
int[] orig;
public Solution(int[] nums) {
this.orig = nums;
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return orig;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] arr = orig.clone();
Random r = new Random();
for (int i = arr.length - 1; i > 0; i--){
int j = r.nextInt(i + 1);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
}
/**
* 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 {
int[] orig;
public Solution(int[] nums) {
this.orig = nums;
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return orig;
}
//r.nextInt((max - min) + 1) + min;
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] arr = orig.clone();
Random rand = new Random();
for (int i = 0; i < arr.length - 1; i++){
//pick randrom j that 0 <= j <= i
int j = rand.nextInt(arr.length - 1 - i + 1) + i;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
}
/**
* 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();
*/
高能重点来了,面经里看到别人被问:
a. When do shuffling, how to make sure each num is picked equally? Prove it.
b. How many permutation can you get? n!