Python solution keeps getting TLE, but my Java implementation works


  • 0
    Z

    Using the exact same Fisher-Yates algorithm:

    Python solution

    from random import randint

    class Solution(object):

    def __init__(self, nums):
        """
        
        :type nums: List[int]
        :type size: int
        """
        self.nums = nums
        
    
    def reset(self):
        """
        Resets the array to its original configuration and return it.
        :rtype: List[int]
        """
        return self.nums
    
    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        shuffle = self.nums[:]
        l = len(shuffle)
        for i in range(0, l-1):
            r = int(random.random()*(l-i))+i
            shuffle[i], shuffle[r] = shuffle[r], shuffle[i]
        return shuffle
    

    Java solution:

    public class Solution {
    private int[] nums;
    public Solution(int[] nums) {
    this.nums = nums;
    }

    public int[] reset() {
        return this.nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] a = this.nums.clone();
        for(int i = 0; i < a.length-1; i++){
            int rand = (int)(Math.random()*(a.length-i))+i;
            // System.out.println(rand);
            int tmp = a[i];
            a[i] = a[rand];
            a[rand] = tmp;
        }
        return a;
    }
    

    }

    This is really weird. Has anyone else had the same problem?


Log in to reply
 

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