打乱数组。给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。实现 Solution class:Solutio(int[] nums) 使用整数数组 nums
  zNRyot8onCGb 2024年05月17日 51 0

打乱数组。给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。实现 Solution class:Solutio(int[] nums) 使用整数数组 nums 初始化对象;int[] reset() 重设数组到它的初始状态并返回;int[] shuffle() 返回数组随机打乱后的结果 。力扣384。

第1次,1到N-1取随机数i1,[i1]与[N-1]交换。
第2次,1到N-2取随机数i2,[i2]与[N-2]交换。
遍历下去,就是打乱的数组了。
时间复杂度:O(N)。
额外空间复杂度:O(N)。因为有重置功能。

代码用golang编写。代码如下:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    c := Constructor(arr)
    fmt.Println(c.Shuffle())
}

type Solution struct {
    origin  []int
    shuffle []int
    N       int
}

func Constructor(nums []int) Solution {
    res := Solution{}
    res.origin = nums
    res.N = len(nums)
    res.shuffle = make([]int, res.N)
    for i := 0; i < res.N; i++ {
        res.shuffle[i] = res.origin[i]
    }
    return res
}

func (this *Solution) Reset() []int {
    return this.origin
}

func (this *Solution) Shuffle() []int {
    for i := this.N - 1; i >= 0; i-- {
        //int r = (int) (Math.random() * (i + 1));
        r := rand.Intn(i + 1)
        tmp := this.shuffle[r]
        this.shuffle[r] = this.shuffle[i]
        this.shuffle[i] = tmp
    }
    return this.shuffle
}

执行结果如下:

2021-11-11:打乱数组。给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。实现 Solution class:Solutio(int[] nums) 使用整数数组 nums

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年05月17日 0

暂无评论

推荐阅读
  zNRyot8onCGb   2024年05月17日   59   0   0 算法i++
zNRyot8onCGb