Skip to content

Commit 79079c6

Browse files
committed
add: leetcode 0384 readme
1 parent f8a3773 commit 79079c6

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# [384.Shuffle an Array](https://leetcode-cn.com/problems/shuffle-an-array/)
2+
3+
## 题目
4+
5+
Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
6+
7+
Implement the Solution class:
8+
9+
- Solution(int[] nums) Initializes the object with the integer array nums.
10+
- int[] reset() Resets the array to its original configuration and returns it.
11+
- int[] shuffle() Returns a random shuffling of the array.
12+
13+
**Example 1**:
14+
15+
Input
16+
["Solution", "shuffle", "reset", "shuffle"]
17+
[[[1, 2, 3]], [], [], []]
18+
Output
19+
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
20+
21+
Explanation
22+
Solution solution = new Solution([1, 2, 3]);
23+
solution.shuffle(); // Shuffle the array [1,2,3] and return its result.
24+
// Any permutation of [1,2,3] must be equally likely to be returned.
25+
// Example: return [3, 1, 2]
26+
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
27+
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
28+
29+
**Constraints:**
30+
31+
- 1 <= nums.length <= 200
32+
- -1000000 <= nums[i] <= 1000000
33+
- All the elements of nums are unique.
34+
- At most 5 * 10000 calls in total will be made to reset and shuffle.
35+
36+
## 题目大意
37+
38+
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。
39+
40+
实现 Solution class:
41+
42+
- Solution(int[] nums) 使用整数数组 nums 初始化对象
43+
- int[] reset() 重设数组到它的初始状态并返回
44+
- int[] shuffle() 返回数组随机打乱后的结果
45+
46+
## 解题思路
47+
48+
- 使用rand.Shuffle进行数组随机打乱
49+
50+
## 代码
51+
52+
```go
53+
package leetcode
54+
55+
import "math/rand"
56+
57+
type Solution struct {
58+
nums []int
59+
}
60+
61+
func Constructor(nums []int) Solution {
62+
return Solution{
63+
nums: nums,
64+
}
65+
}
66+
67+
/** Resets the array to its original configuration and return it. */
68+
func (this *Solution) Reset() []int {
69+
return this.nums
70+
}
71+
72+
/** Returns a random shuffling of the array. */
73+
func (this *Solution) Shuffle() []int {
74+
arr := make([]int, len(this.nums))
75+
copy(arr, this.nums)
76+
rand.Shuffle(len(arr), func(i, j int) {
77+
arr[i], arr[j] = arr[j], arr[i]
78+
})
79+
return arr
80+
}
81+
```

0 commit comments

Comments
 (0)