Skip to content

Latest commit

 

History

History
76 lines (51 loc) · 1.5 KB

384.md

File metadata and controls

76 lines (51 loc) · 1.5 KB

384 Shuffle an Array

Description

link


Solution

  • See Code

Code

class Solution:

    def __init__(self, nums: List[int]):
        self.origin = nums
        

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

    def shuffle(self) -> List[int]:
        """
        Returns a random shuffling of the array.
        """
        res = self.origin[:]
        random.shuffle(res)
        return res


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


# Solution 2

class Solution:

    def __init__(self, nums: List[int]):
        self.origin = nums
        

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

    def shuffle(self) -> List[int]:
        """
        Returns a random shuffling of the array.
        """
        ans = self.origin[:]                     # copy list
        for i in range(len(ans)-1, 0, -1):     # start from end
            j = random.randrange(0, i+1)       # generate random index 
            ans[i], ans[j] = ans[j], ans[i]    # swap
        return ans


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