File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://leetcode.com/problems/shuffle-an-array/
2+ //
3+ // algorithms
4+ // Medium (49.88%)
5+ // Total Accepted: 74,127
6+ // Total Submissions: 148,648
7+
8+
9+ class Solution {
10+
11+ private int [] nums ;
12+
13+ public Solution (int [] nums ) {
14+ this .nums = nums ;
15+ }
16+
17+ /** Resets the array to its original configuration and return it. */
18+ public int [] reset () {
19+ return nums ;
20+ }
21+
22+ /** Returns a random shuffling of the array. */
23+ public int [] shuffle () {
24+ int [] curNums = this .nums .clone ();
25+ int length = curNums .length ;
26+ int tail = length ;
27+
28+ Random random = new Random ();
29+
30+ for (int i = 0 ; i < length - 1 ; i ++) {
31+ int idx = random .nextInt (tail );
32+ swap (curNums , idx , tail - 1 );
33+ tail --;
34+ }
35+
36+ return curNums ;
37+ }
38+
39+ public void swap (int [] nums , int i , int j ) {
40+ int tmp = nums [i ];
41+ nums [i ] = nums [j ];
42+ nums [j ] = tmp ;
43+ }
44+ }
45+
46+ /**
47+ * Your Solution object will be instantiated and called as such:
48+ * Solution obj = new Solution(nums);
49+ * int[] param_1 = obj.reset();
50+ * int[] param_2 = obj.shuffle();
51+ */
You can’t perform that action at this time.
0 commit comments