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

相关推荐
郝学胜-神的一滴11 小时前
AI 编程智能体 17:四步搞定专属AI智能体
大数据·人工智能·python·神经网络·算法·langchain·强化学习
微尘hjx11 小时前
【StrongSort 03】多轨迹算法StrongSort改进点
人工智能·算法·yolo·视觉检测·ultralytics·strongsort·轨迹算法
梦帮科技11 小时前
QML-04-QGraph-Diff:量子非欧图扩散生成模型与 SE(3) 等变分子晶格逆向合成完整技术指南(上部分)
人工智能·算法·自动化·量子计算·傅里叶分析
七牛开发者11 小时前
TokenGate:端到端可训练的 Token 剪枝机制,让大模型 Prefill 提速 11.3 倍
算法·机器学习·剪枝·长上下文·tokengate
咚咚咚小柒11 小时前
【前端】LangChain.js学习
前端·javascript·人工智能·typescript·langchain·vue·ai编程
牧瀬クリスだ13 小时前
Redis Hash实战:高效存储对象与购物车
java·数据库·redis·算法·哈希算法
木井巳13 小时前
【动态规划: 路径问题】下降路径最小和
java·算法·leetcode·动态规划·推荐算法
deepseek2314 小时前
OpenAI三项科学发现拆解:3-SAT亚指数算法挑战ETH,AI科学声明的验证流水线怎么搭
人工智能·算法·openai
梦帮科技14 小时前
基于幺正李代数连续归一化流的混合量子生成模型 (HQNN-Flow) 完整技术指南(上部分)
网络·人工智能·算法·量子计算