题目
解题思路
/*n is the size of the array[0...n - 1]i [i, n-1]i = 0, [0, n - 1] 1 / ni = 1, [1, n - 1] ( (n - 1) / n ) * ( 1 /(n - 1)) = 1 /i = 2 ( (n - 1) / n ) * ( n - 2 /(n - 1)) * (n - 2 / n - 1) = 1 / n[i, n - 1][0, n - 1 - i] + i*/
作者:venturekwok
链接:https://leetcode-cn.com/problems/shuffle-an-array/solution/c-jian-dan-xi-pai-suan-fa-si-lu-qing-xi-pu41a/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解题代码
class Solution {int[] nums;//构造函数,初始化public Solution(int[] nums) {this.nums = nums;}//重置public int[] reset() {return nums;}//洗牌算法public int[] shuffle() {if(nums == null) return null;int[] res = nums.clone();for(int i = 0 ; i < nums.length; i++ ) {int random = (int) ( Math.random() * (nums.length - i) ) + i; //[0,1) [i,nums.length -1]swap(res,i,random);}return res;}public void swap(int[] res, int i, int random) {int temp = res[i];res[i] = res[random];res[random] = 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();*/
class Solution {
int [] nums;
int [] shuffle;
public Solution(int[] nums) {
this.nums = nums;
}
public int[] reset() {
return nums;
}
public int[] shuffle() {
int length = nums.length;
shuffle = nums.clone(); //传值
for (int i = 0; i < length; i++) {
int random = (int)(Math.random() * (length - i )) + i;
swap(i,random);
}
return shuffle;
}
public void swap(int i ,int j) {
if(i == j) return ; //相同则不进行交换
shuffle[i] ^= shuffle[j];
shuffle[j] ^= shuffle[i];
shuffle[i] ^= shuffle[j];
}
}
/**
* 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();
*/
