美文网首页
Leetcode_384_打乱数组_hn

Leetcode_384_打乱数组_hn

作者: 1只特立独行的猪 | 来源:发表于2020-03-14 13:10 被阅读0次

    题目描述

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

    示例

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

    解答方法

    方法一:洗牌算法

    思路

    https://leetcode-cn.com/problems/shuffle-an-array/solution/da-luan-shu-zu-by-leetcode/

    代码

    class Solution:
    
        def __init__(self, nums: List[int]):
            self.nums = nums
            
    
        def reset(self) -> List[int]:
            """
            Resets the array to its original configuration and return it.
            """
            return self.nums
    
        def shuffle(self) -> List[int]:
            """
            Returns a random shuffling of the array.
            """
            array = copy.copy(self.nums)
            for i in range(len(array)):
                idx = random.randint(i, len(array)-1)
                array[i],array[idx] = array[idx], array[i]
            return array
    
    
    # Your Solution object will be instantiated and called as such:
    # obj = Solution(nums)
    # param_1 = obj.reset()
    # param_2 = obj.shuffle()
    

    时间复杂度

    O(n),Fisher-Yates 洗牌算法时间复杂度是线性的,因为算法中生成随机序列,交换两个元素这两种操作都是常数时间复杂度的。

    空间复杂度

    O(n),因为要实现重置功能,原始数组必须得保存一份,因此空间复杂度并没有优化。

    相关文章

      网友评论

          本文标题:Leetcode_384_打乱数组_hn

          本文链接:https://www.haomeiwen.com/subject/nbyvshtx.html