题目:打乱数组
打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
------------------------------------------------------------------------------------------
思路:通过Fisher–Yates shuffle 洗牌算法来实现。(该算法的详细解释见参考1)
简单来说 Fisher–Yates shuffle 算法是一个用来将一个有限集合生成一个随机排列的算法(数组随机排序)。这个算法生成的随机排列是等概率的。同时这个算法非常高效。
解法1:
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.nums
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
# 不改变原数组,复制原数组生成一个新数组
nums2 = self.nums[:]
l = len(nums_)
for i in range(l):
# 随机生成一个i到l的下标数
n = random.randrange(i, l)
nums2[i], nums2[n] = nums2[n], nums2[i]
return nums2
解法2:解法1的另一种写法表达
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.origin = nums[:]
self.output = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.origin
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
for i in range(len(self.output)):
j = random.randint(i, len(self.output) - 1)
self.output[i], self.output[j] = self.output[j], self.output[i]
return self.output
参考:
https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/