Skip to content

Commit 7ea359b

Browse files
committed
solve 384.shuffle-an-array
1 parent 866efd8 commit 7ea359b

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

vscode/384.shuffle-an-array.java

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
* @lc app=leetcode id=384 lang=java
3+
*
4+
* [384] Shuffle an Array
5+
*
6+
* https://leetcode.com/problems/shuffle-an-array/description/
7+
*
8+
* algorithms
9+
* Medium (49.48%)
10+
* Total Accepted: 73.5K
11+
* Total Submissions: 147.4K
12+
* Testcase Example: '["Solution","shuffle","reset","shuffle"]\n[[[1,2,3]],[],[],[]]'
13+
*
14+
* Shuffle a set of numbers without duplicates.
15+
*
16+
*
17+
* Example:
18+
*
19+
* // Init an array with set 1, 2, and 3.
20+
* int[] nums = {1,2,3};
21+
* Solution solution = new Solution(nums);
22+
*
23+
* // Shuffle the array [1,2,3] and return its result. Any permutation of
24+
* [1,2,3] must equally likely to be returned.
25+
* solution.shuffle();
26+
*
27+
* // Resets the array back to its original configuration [1,2,3].
28+
* solution.reset();
29+
*
30+
* // Returns the random shuffling of array [1,2,3].
31+
* solution.shuffle();
32+
*
33+
*
34+
*/
35+
class Solution {
36+
int[] array;
37+
int[] original;
38+
39+
Random random = new Random();
40+
41+
public Solution(int[] nums) {
42+
array = nums;
43+
original = nums.clone();
44+
}
45+
46+
/** Resets the array to its original configuration and return it. */
47+
public int[] reset() {
48+
array = original;
49+
original = original.clone();
50+
return original;
51+
}
52+
53+
/** Returns a random shuffling of the array. */
54+
public int[] shuffle() {
55+
int len = array.length;
56+
for (int i = 0; i < len; i++) {
57+
swap(array, i, rand(i, len));
58+
}
59+
return array;
60+
}
61+
62+
public int rand(int min, int max) {
63+
return random.nextInt(max - min) + min;
64+
}
65+
66+
public void swap(int[] nums, int i, int j) {
67+
if (i == j) return;
68+
int temp = nums[i];
69+
nums[i] = nums[j];
70+
nums[j] = temp;
71+
}
72+
}
73+
74+
/**
75+
* Your Solution object will be instantiated and called as such:
76+
* Solution obj = new Solution(nums);
77+
* int[] param_1 = obj.reset();
78+
* int[] param_2 = obj.shuffle();
79+
*/
80+

0 commit comments

Comments
 (0)