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

相关推荐
Swift社区4 分钟前
LeetCode 380 O(1) 时间插入、删除和获取随机元素
算法·leetcode·职场和发展
budingxiaomoli4 分钟前
优选算法-哈希表
数据结构·算法·散列表
高频交易dragon11 分钟前
An Impulse Control Approach to Market Making in a Hawkes LOB Market从论文到生产
人工智能·算法·机器学习
EndingCoder37 分钟前
反射和元数据:高级装饰器用法
linux·运维·前端·ubuntu·typescript
java修仙传37 分钟前
力扣hot100:划分字母区间
算法·leetcode·职场和发展
Frank_refuel40 分钟前
C++STL之set和map的接口使用介绍
数据库·c++·算法
java修仙传41 分钟前
力扣hot100:跳跃游戏||
算法·leetcode·游戏
闻缺陷则喜何志丹42 分钟前
【模拟】P9670 [ICPC 2022 Jinan R] Frozen Scoreboard|普及+
c++·算法·模拟·洛谷
永远都不秃头的程序员(互关)1 小时前
【K-Means深度探索(十一)】K-Means VS 其他聚类算法:如何选择最合适的工具?
算法·kmeans·聚类
洛生&1 小时前
Nested Ranges Count
算法