Leetcode 384

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

示例:

// 以数字集合 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功能,因此不能给予太多的建议。

class Solution(object):

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

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

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        length = len(self.output)
        for i in range(length):
            j = random.randint(i, length-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()

猜你喜欢

转载自blog.csdn.net/jhlovetll/article/details/85870201