前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2021-11-11:打乱数组。给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。实现 Solution cl

2021-11-11:打乱数组。给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。实现 Solution cl

作者头像
福大大架构师每日一题
发布2021-11-16 10:33:35
5200
发布2021-11-16 10:33:35
举报
文章被收录于专栏:福大大架构师每日一题

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

答案2021-11-11:

第1次,1到N-1取随机数i1,[i1]与[N-1]交换。

第2次,1到N-2取随机数i2,[i2]与[N-2]交换。

遍历下去,就是打乱的数组了。

时间复杂度:O(N)。

额外空间复杂度:O(N)。因为有重置功能。

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

代码语言:javascript
复制
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
}

执行结果如下:

[左神java代码](https://github.com/algorithmzuo/coding-for-great-offer/blob/main/src/class34/Problem_0384_ShuffleAnArray.java)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-11-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 福大大架构师每日一题 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档