384.打乱数组

https://leetcode-cn.com/problems/shuffle-an-array/

就是洗牌算法。注意py中for循环次数不会随变量改变而改变,一开始就已定好

import random
class Solution:

    def __init__(self, nums: List[int]):
        self.nums = nums
        self.origin = list(nums)	#存储原始数组备用

    def reset(self) -> List[int]:
        self.nums = list(self.origin)	#直接拿原始数组
        return self.nums

    def shuffle(self) -> List[int]:
        shuffle = [0] * len(self.nums)	#洗牌数组
        # 每次从0 ~ len(nums)-1个位置中选一个数字弹出,放入洗牌数组
        for i in range(len(self.nums)):	
            j = random.randrange(len(self.nums))
            shuffle[i] = self.nums.pop(j)
        self.nums = shuffle
        return self.nums

最后更新于