Need help. Works fine in many test cases, but got a limit time exceeded err when I submitted it


  • -2
    C

    Do anyone know where is the error?
    This code works fine in both odd and even length input,
    however it got a limit time exceeded error when I submit it.

    class Solution(object):
    def wiggleSort(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        # Find a median and put elements, which are smaller than median, in the first half of array.
        # Adapted from selection algorithm.
        array = nums[:]
        #array.sort()
        k = n/2
        for i in range(0, k+1):
            minIdx = i
            minValue = array[i]
            for j in range(i+1, n):
                if array[j] < minValue:
                    minIdx = j
                    minValue = array[j]
            array[i], array[minIdx] = array[minIdx], array[i]
        mid = array[k]
    
        # Put elements, which are equal to median, after the first half of array.
        for i in range(k+1, n):
            if array[i] == mid:
                k = k+1
                array[k], array[i] = array[i], array[k]
        
        # Fill elements into nums from array
        # even idx (small): fetch from the first half of array (smaller elements)
        # odd idx (big): fetch from the second half of array (bigger elements)
        for i in range(0, n):
            if i%2: nums[i] = array[n-i/2-1]
            else: nums[i] = array[(n-1)/2-i/2]

Log in to reply
 

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