打乱一个没有重复元素的数组。
image.pnggolang代码:
package shuffle
import (
"math/rand"
"time"
)
type Solution struct {
array []int
backup []int //备份
}
func Constructor(nums []int) Solution {
return Solution{
backup: append([]int{}, nums...),
array: append([]int{}, nums...),
}
}
// Reset the array to its original configuration and return it.
func (this *Solution) Reset() []int {
this.array = this.backup
return this.backup
}
func (this *Solution) Shuffle() []int {
if this.array == nil {
return nil
}
for i := 1; i < len(this.array); i++ {
p := RandInt64_(0, int64(i))
a := this.array[i]
this.array[i] = this.array[p]
this.array[p] = a
}
return this.array
}
// RandInt64_ 区间随机数
func RandInt64_(min, max int64) int64 {
if min >= max || max == 0 {
return max
}
return rand.Int63n(max-min) + min + 1
}
网友评论