-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path384. Shuffle an Array.java
More file actions
38 lines (34 loc) · 945 Bytes
/
Copy path384. Shuffle an Array.java
File metadata and controls
38 lines (34 loc) · 945 Bytes
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
public class Solution {
int[] array;
Random rand;
public Solution(int[] nums) {
this.array = nums;
rand = new Random();
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return array;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] temp = array.clone();
for (int i = 1; i <= temp.length; i++) {
int random = rand.nextInt(i);
if (random != i - 1) {
swap(temp,i-1,random);
}
}
return temp;
}
public void swap(int[] nums, int x, int y) {
int temp = nums[x];
nums[x] = nums[y];
nums[y] = 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();
*/