题目链接:384. 打乱数组 - 力扣(LeetCode)

先从一道没什么技术含量的题开始了。本题引入了Fisher Yates洗牌算法原理,其实质是相同概率下的元素选取和交换:从后向前(或从前向后)遍历数组,将当前遍历到的元素与其前面(后面)的任意数字交换后固定不变。取随机数的过程调用了java的Random类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// java解法——从后向前
import java.util.*;

class Solution {

private int[] ori;
private int[] nums;
public Solution(int[] nums) {
this.nums = nums;
this.ori = nums.clone();
}

/** Resets the array to its original configuration and return it. */
public int[] reset() {
return this.ori;
}

/** Returns a random shuffling of the array. */
public int[] shuffle() {
Random random = new Random();
int length = nums.length;
for(int i = length - 1; i > 1; i--) {
int j = random.nextInt(i + 1);
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
return nums;
}
}

/**
* 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();
*/

python的话,import random也可以达到相同效果:

1
2
3
4
5
def shuffle(self):
for i in range(len(self.output)):
j = random.randint(i, len(self.output) - 1)
self.output[i], self.output[j] = self.output[j], self.output[i]
return self.output