1. 题目
打乱一个没有重复元素的数组。
示例:
// 以数字集合 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();
2. 优答
思路参考的这个博客:https://www.cnblogs.com/grandyang/p/5783392.html
这个题目要求每个排列是等概率的,需要使用Knuth shuffle算法(参考https://yjk94.wordpress.com/2017/03/17/%E6%B4%97%E7%89%8C%E7%9A%84%E6%AD%A3%E7%A1%AE%E5%A7%BF%E5%8A%BF-knuth-shuffle%E7%AE%97%E6%B3%95/)
import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type size: 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] """ nums = list(self.__nums) for i in range(len(nums)): j = random.randint(i, len(nums)-1) ###这边很容易出错,如果写成random.randint(0,len(nums)-1),那么每个排列就不是等概率了。 nums[i], nums[j] = nums[j], nums[i] return nums nums = [1,2,3] obj = Solution(nums) p1 = obj.reset() p2 = obj.shuffle() print(p1) print(p2)