python_leetcode384. 打乱数组

打乱一个没有重复元素的数组。

示例:

// 以数字集合 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();

想法:主要重点在shuffle

(一)洗牌算法实现

洗牌原始方法:

  1. 写下从 1 到 N 的数字
  2. 取一个从 1 到剩下的数字(包括这个数字)的随机数 k
  3. 从低位开始,得到第 k 个数字(这个数字还没有被取出),把它写在独立的一个列表的最后一位
  4. 重复第 2 步,直到所有的数字都被取出
  5. 第 3 步写出的这个序列,现在就是原始数字的随机排列

改进后:

在每次迭代时交换这个被取出的数字到原始列表的最后。这样就将时间复杂度从 O(n^2) 减小到了 O(n)

同样的可以放置在最前面

即:

class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.orgin = nums[:]
        self.output = nums
        

    def reset(self):
        """
        Resets the array to its original configuration and return it.
        :rtype: List[int]
        """
        return self.orgin
        

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        n = len(self.output)
        for i in range(n):
            j = random.randint(i,n-1)
            self.output[i], self.output[j] = self.output[j], self.output[i]
        return self.output
        
        


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

参考https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/

(二)直接使用shuffle

class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.orgin = nums[:]
        self.output = nums
        

    def reset(self):
        """
        Resets the array to its original configuration and return it.
        :rtype: List[int]
        """
        return self.orgin
        

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        # n = len(self.output)
        # for i in range(n):
        #     j = random.randint(i,n-1)
        #     self.output[i], self.output[j] = self.output[j], self.output[i]
        # return self.output
        random.shuffle(self.output)
        return self.output
        


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

猜你喜欢

转载自blog.csdn.net/AntiZheng/article/details/82734895