File tree 2 files changed +41
-0
lines changed
2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 281
281
378|[ Kth Smallest Element in a Sorted Matrix] ( ./0378-kth-smallest-element-in-a-sorted-matrix.js ) |Medium|
282
282
380|[ Insert Delete GetRandom O(1)] ( ./0380-insert-delete-getrandom-o1.js ) |Medium|
283
283
383|[ Ransom Note] ( ./0383-ransom-note.js ) |Easy|
284
+ 384|[ Shuffle an Array] ( ./0384-shuffle-an-array.js ) |Medium|
284
285
387|[ First Unique Character in a String] ( ./0387-first-unique-character-in-a-string.js ) |Easy|
285
286
389|[ Find the Difference] ( ./0389-find-the-difference.js ) |Easy|
286
287
392|[ Is Subsequence] ( ./0392-is-subsequence.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 384. Shuffle an Array
3
+ * https://leetcode.com/problems/shuffle-an-array/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an integer array nums, design an algorithm to randomly shuffle the array.
7
+ * All permutations of the array should be equally likely as a result of the shuffling.
8
+ *
9
+ * Implement the Solution class:
10
+ * - Solution(int[] nums) Initializes the object with the integer array nums.
11
+ * - int[] reset() Resets the array to its original configuration and returns it.
12
+ * - int[] shuffle() Returns a random shuffling of the array.
13
+ */
14
+
15
+ /**
16
+ * @param {number[] } nums
17
+ */
18
+ var Solution = function ( nums ) {
19
+ this . original = [ ...nums ] ;
20
+ this . result = [ ...nums ] ;
21
+ } ;
22
+
23
+ /**
24
+ * @return {number[] }
25
+ */
26
+ Solution . prototype . reset = function ( ) {
27
+ this . result = [ ...this . original ] ;
28
+ return this . result ;
29
+ } ;
30
+
31
+ /**
32
+ * @return {number[] }
33
+ */
34
+ Solution . prototype . shuffle = function ( ) {
35
+ for ( let i = this . result . length - 1 ; i > 0 ; i -- ) {
36
+ const j = Math . floor ( Math . random ( ) * ( i + 1 ) ) ;
37
+ [ this . result [ i ] , this . result [ j ] ] = [ this . result [ j ] , this . result [ i ] ] ;
38
+ }
39
+ return this . result ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments