Skip to content

Commit acda3d3

Browse files
committedFeb 21, 2025
Add solution #384
1 parent af0b47e commit acda3d3

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@
281281
378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium|
282282
380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium|
283283
383|[Ransom Note](./0383-ransom-note.js)|Easy|
284+
384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium|
284285
387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy|
285286
389|[Find the Difference](./0389-find-the-difference.js)|Easy|
286287
392|[Is Subsequence](./0392-is-subsequence.js)|Easy|

‎solutions/0384-shuffle-an-array.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
};

0 commit comments

Comments
 (0)
Please sign in to comment.