Golang:
思路:实现不难,这里注意,go提供了库函数可以打乱数组,但这里依然使用了手写来实现
代码如下:
type Solution struct {
src []int
}
func Constructor(nums []int) Solution {
return Solution{src:nums}
}
/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
return this.src
}
/** Returns a random shuffling of the array. */
func (this *Solution) Shuffle() []int {
length:=len(this.src)
cpy:=make([]int,length)
shuffle:=make([]int,length)
copy(cpy,this.src)
for i:=0;i<len(shuffle);i++{
temp:=rand.Intn(len(cpy))
shuffle[i]=cpy[temp]
cpy=append(cpy[:temp],cpy[temp+1:]...)
}
return shuffle
}
有疑问加站长微信联系(非本文作者)