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

相关推荐
笨笨饿10 分钟前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发
纽扣6671 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
消失的旧时光-19431 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
智者知已应修善业1 小时前
【51单片机不用数组动态数码管显示字符和LED流水灯】2023-10-3
c++·经验分享·笔记·算法·51单片机
AI进化营-智能译站2 小时前
ROS2 C++开发系列16-智能指针管理传感器句柄|告别ROS2节点内存泄漏与野指针
java·c++·算法·ai
CS创新实验室3 小时前
从盘边到芯端——硬盘接口七十年变迁史
算法·磁盘调度
xvhao20133 小时前
单源、多源最短路
数据结构·c++·算法·深度优先·动态规划·图论·图搜索算法
MATLAB代码顾问3 小时前
多种群协同进化算法(MPCE)求解大规模作业车间调度问题——附MATLAB代码
开发语言·算法·matlab
FQNmxDG4S3 小时前
JVM内存模型详解:堆、栈、方法区与垃圾回收
java·jvm·算法
We་ct4 小时前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划