美文网首页
(初级)7.Shuffle an Array

(初级)7.Shuffle an Array

作者: one_zheng | 来源:发表于2018-08-11 16:15 被阅读5次

    打乱一个没有重复元素的数组。

    image.png

    golang代码:

    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
    }
    

    相关文章

      网友评论

          本文标题:(初级)7.Shuffle an Array

          本文链接:https://www.haomeiwen.com/subject/kcqfbftx.html