-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Solution.java
46 lines (37 loc) · 992 Bytes
/
Solution.java
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
38
39
40
41
42
43
44
45
46
package 数组操作.q384_打乱数组;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* 洗牌算法 o(n)
*/
public class Solution {
private int[] array;
private int[] original;
private Random rand = new Random();
private List<Integer> getArrayCopy() {
List<Integer> asList = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
asList.add(array[i]);
}
return asList;
}
public Solution(int[] nums) {
array = nums;
original = nums.clone();
}
public int[] reset() {
array = original;
original = original.clone();
return array;
}
public int[] shuffle() {
List<Integer> aux = getArrayCopy();
for (int i = 0; i < array.length; i++) {
int removeIdx = rand.nextInt(aux.size());
array[i] = aux.get(removeIdx);
aux.remove(removeIdx);
}
return array;
}
}