算法(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)

相关推荐
wuweijianlove4 分钟前
算法复杂度估算的实验建模与可视化表达的技术6
算法
执笔画流年呀5 分钟前
7大排序算法
java·算法·排序算法
AI成长日志10 分钟前
【算法学习专栏】动态规划基础·中等两题精讲(198.打家劫舍、322.零钱兑换)
学习·算法·动态规划
计算机安禾13 分钟前
【数据结构与算法】第28篇:平衡二叉树(AVL树)
开发语言·数据结构·数据库·线性代数·算法·矩阵·visual studio
测试_AI_一辰13 分钟前
AI 如何参与 Playwright 自动化维护:一次自动修复闭环实践
人工智能·算法·ai·自动化·ai编程
未来之窗软件服务26 分钟前
算法设计—计算机等级考试—软件设计师考前备忘录—东方仙盟
算法·软件设计师·计算机等级考试
未来之窗软件服务29 分钟前
哈夫曼树构造—计算机等级考试—软件设计师考前备忘录—东方仙盟
算法·软件设计师·计算机等级考试·仙盟创梦ide·东方仙盟
SUNNY_SHUN1 小时前
VLM走进农田:AgriChat覆盖3000+作物品类,607K农业视觉问答基准开源
论文阅读·人工智能·算法·开源
黎阳之光1 小时前
视频孪生赋能车路云一体化,领跑智慧高速新征程
人工智能·算法·安全·数字孪生
Darkwanderor2 小时前
高精度计算——基础模板整理
c++·算法·高精度计算