LeetCode:Shuffle an Array(打乱数组)(Python版本)

LeetCode刷题日记

  • Shuffle an Array(打乱数组)
    • Python代码

Shuffle an Array(打乱数组)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/

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

示例:

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

Python代码

PS:这里reset()利用了tuple为不可变对象的原理。

class Solution(object):

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

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

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        import random
        x = self.nums
        _int = int
        for i in reversed(range(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
            j = _int(random.random() * (i + 1))
            x[i], x[j] = x[j], x[i]
        return x

执行用时 : 276 ms, 在Shuffle an Array的Python提交中击败了96.70% 的用户
内存消耗 : 17.4 MB, 在Shuffle an Array的Python提交中击败了6.08% 的用户

在题解看到了一种写法,也可以作为参考,大体类似。传送门

import random

class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.init = list(nums)
        self.nums = nums
        self.length = len(nums)
        
        

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

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        for i in reversed(range(self.length)):
            index = random.randint(0, i)
            self.nums[i], self.nums[index] = self.nums[index], self.nums[i]
        return self.nums

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

你可能感兴趣的:(Python,设计问题)