法一:暴力洗牌法
不懂:self.array已经是list形式了,为什么aux还要再list一次呢?以下几个list少一个,换换地方都不行。
执行用时:212 ms, 在所有 Python3 提交中击败了74.98%的用户
内存消耗:20.2 MB, 在所有 Python3 提交中击败了45.17%的用户
class Solution:
def __init__(self, nums: List[int]):
self.array=list(nums)#十分必要
self.original=nums
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
self.array=list(self.original)#十分必要
return self.array
def shuffle(self) -> List[int]:
"""
Returns a random shuffling of the array.
"""
aux=list(self.array)#十分必要
for i in range(len(self.array)):
remove_id=random.randrange(len(aux))
self.array[i]=aux.pop(remove_id)
return self.array
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
法二:Fisher-Yates 洗牌算法
重点:交换代替删除元素
执行用时:228 ms, 在所有 Python3 提交中击败了58.48%的用户
内存消耗:20.2 MB, 在所有 Python3 提交中击败了17.57%的用户
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
self.array=list(self.original)
return self.array
def shuffle(self) -> List[int]:
"""
Returns a random shuffling of the array.
"""
for i in range(len(self.array)):
swap_id=random.randrange(i,len(self.array))
self.array[i],self.array[swap_id]=self.array[swap_id],self.array[i]
return self.array