算法(TS):打乱数组

给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是 等可能 的。

实现 Solution class:

  • Solution(int[] nums) 使用整数数组 nums 初始化对象
  • int[] reset() 重设数组到它的初始状态并返回
  • int[] shuffle() 返回数组随机打乱后的结果

解释

Solution solution = new Solution([1, 2, 3]);

solution.shuffle(); // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2]

solution.reset(); // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]

solution.shuffle(); // 随机返回数组 [1, 2, 3] 打乱后的结果。例如,返回 [1, 3, 2]

提示:

  • 1 <= nums.length <= 50
  • -106 <= nums[i] <= 106
  • nums 中的所有元素都是 唯一的
  • 最多可以调用 104 次 reset 和 shuffle

解法一

用 Math.random() 生成随机数从 nums 取值,将取出来的值从数组中移除,添加到新数组中,当 nums 中的数取完之后,将新数组返回。

ts 复制代码
class Solution {
    private nums: number[] = []
    constructor(nums: number[]) {
        this.nums = nums
    }

    reset(): number[] {
        return this.nums
    }

    shuffle(): number[] {
        const thisNums = this.nums.concat()
        const result: number[] = []
        while(thisNums.length) {
            let i = Math.floor(Math.random() * thisNums.length)
            result.push(thisNums[i])
            thisNums.splice(i,1)
        }
        return result

    }
}

空间复杂度O(n),时间复杂度O(n * n)

解法二:洗牌算法

用 Math.random() 生成坐标从 nums 取值,将取出来的数与数组最后一个元素交换,接下来从剩下的数字中取值。

ts 复制代码
class Solution {
    private nums: number[] = []
    constructor(nums: number[]) {
        this.nums = nums
    }

    reset(): number[] {
        return this.nums
    }

    shuffle(): number[] {
        const shuffle = this.nums.concat()
        let lastIndex = result.length - 1
        while(lastIndex > 0) {
            const i = Math.floor(Math.random() * (lastIndex + 1))
            const temp = shuffle[i]
            shuffle[i] = shuffle[lastIndex]
            shuffle[lastIndex] = temp
            lastIndex--
        }
        return shuffle

    }
}

时间复杂度O(n),空间复杂度O(n)

相关推荐
zhangzuying102610 分钟前
基于Vue3 +ElementuiPlus + Dexie.js自研的浏览器插件新建标签页tab
vue.js·typescript·echarts
一只乔哇噻12 分钟前
java后端工程师进修ing(研一版 || day41)
java·开发语言·学习·算法
愚润求学14 分钟前
【贪心算法】day7
c++·算法·leetcode·贪心算法
要开心吖ZSH40 分钟前
软件设计师备考-(十六)数据结构及算法应用(重要)
java·数据结构·算法·软考·软件设计师
带娃的IT创业者1 小时前
如何开发一个教育性质的多线程密码猜测演示器
网络·python·算法
Aczone282 小时前
硬件(六)arm指令
开发语言·汇编·arm开发·嵌入式硬件·算法
luckys.one7 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|8 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师8 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo38 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘