384. 打乱数组(重置、随机)(Medium)

384. 打乱数组(重置、随机)(Medium)

class Solution:

    def __init__(self, nums: List[int]):
        self.array = nums
        self.original = list(nums) # 保存原始数组

    def reset(self) -> List[int]:
        """
        Resets the array to its original configuration and return it.
        """
        self.array = self.original
        self.original = list(self.original)
        return self.array


    def shuffle(self) -> List[int]:
        """
        Returns a random shuffling of the array.
        """
        # 随机n次,任何一个元素都会以等可能的概率被选中
        for i in range(len(self.array)):
            # 随机得到一个下标,再进行交换
            swap_idx = random.randrange(i, len(self.array))
            self.array[i], self.array[swap_idx] = self.array[swap_idx], self.array[i]
        return self.array


# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

384. 打乱数组(重置、随机)(Medium)

上一篇:磁盘管理与文件系统


下一篇:LeetCode283 移动零