384. Shuffle an Array
需要随机生成shuffled array,那直接随机按index取即可。
初始array需要一直被记录着不变。
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
return self.nums
def shuffle(self) -> List[int]:
"""
Returns a random shuffling of the array.
"""
n = len(self.nums)
dep = list(self.nums)
res = [0 for _ in range(n)]
for i in range(n):
res[i] = dep.pop(random.randrange(len(dep)))
return res
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
Last updated
Was this helpful?