# 打乱数组
打乱一个没有重复的数组。
public class UpsetArray {
private int[] array;
private int[] tem;
public UpsetArray(int[] nums) {
this.array = nums;
this.tem = nums.clone();
}
/**
* Resets the array to its original configuration and return it.
* 把数组还原.
*/
public int[] reset() {
array = tem;
tem = tem.clone();
return array;
}
/**
* Returns a random shuffling of the array.
*/
public int[] shuffle() {
for (int i = 0; i < array.length; i++) {
swap(i,random(i,array.length));
}
return array;
}
private void swap(int a, int b) {
int tem = array[a];
array[a] = array[b];
array[b] = tem;
}
private int random(int start, int end) {
Random random = new Random();
return random.nextInt(end - start) + start;
}
}
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
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