Fastest Python solution yet.


  • 0
    I

    Fastest Python solution using built in shuffle. Beat all others just because the shuffled array is cached. Those language writers are pretty smart I guess.

    from random import shuffle
    
    class Solution(object):
    
        def __init__(self, nums):
            self._nums = nums
            self._shuffle_nums = [num for num in nums]
    
        def reset(self):
            return self._nums        
    
        def shuffle(self):
            shuffle(self._shuffle_nums)
            return self._shuffle_nums
    

    And just because I felt bad, without using shuffle but randint. Just iterate through the shuffled list and swap each element with another random one.

    from random import randint
    
    class Solution(object):
    
        def __init__(self, nums):
            self._nums = nums
            self._shuffle_nums = [num for num in nums]
    
        def reset(self):
            return self._nums        
    
        def shuffle(self):
            for i in range(len(self._shuffle_nums)):
                rand_int = randint(0, len(self._shuffle_nums)-1)
                self._shuffle_nums[i], self._shuffle_nums[rand_int] = self._shuffle_nums[rand_int], self._shuffle_nums[i]
    
            return self._shuffle_nums
    

Log in to reply
 

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