Python solution with detailed explanation


  • 0
    G

    Solution

    Shuffle an Array https://leetcode.com/problems/shuffle-an-array/?tab=Description

    from random import randint
    class Solution(object):
        def __init__(self, nums):
            """
            :type nums: List[int]
            :type size: int
            """
            self.original = nums
            return
    
        def reset(self):
            """
            Resets the array to its original configuration and return it.
            :rtype: List[int]
            """
            return [x for x in self.original]
    
        def shuffle(self):
            """
            Returns a random shuffling of the array.
            :rtype: List[int]
            """
            result = [x for x in self.original]
            N = len(self.original)
            for i in range(N):
                x = randint(i, N-1)
                result[i], result[x] = result[x], result[i]
            return result
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.