-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path384.Shuffle-an-Array.go
47 lines (38 loc) · 984 Bytes
/
384.Shuffle-an-Array.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// https://leetcode.com/problems/shuffle-an-array/
//
// algorithms
// Medium (48.9%)
// Total Accepted: 62,460
// Total Submissions: 127,700
// beats 90.48% of golang submissions
package leetcode
import "math/rand"
type Solution struct {
initNums []int
}
func Constructor(nums []int) Solution {
return Solution{
initNums: nums,
}
}
/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
return this.initNums
}
/** Returns a random shuffling of the array. */
func (this *Solution) Shuffle() []int {
length := len(this.initNums)
shuffleNums := make([]int, length)
copy(shuffleNums, this.initNums)
for i := length - 1; i >= 0; i-- {
idx := rand.Intn(i + 1)
shuffleNums[i], shuffleNums[idx] = shuffleNums[idx], shuffleNums[i]
}
return shuffleNums
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.Reset();
* param_2 := obj.Shuffle();
*/