[Python] How about the recursive code for "Find Zero" I've written?

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    Here's the problem:


    Given an array nums, write a function that moves all 0s to the end of the array while maintaining the relative order of the non-zero elements. Please note that the array must be modified in place without creating a copy of the array.
    ​

    Does this code take linear time? If not, should I write the code in a more normal way using two pointers?

    '''Recursively solve the 'Find Zero' problem without a new array created.'''

    def Min_Zero(j, nums):
    while nums[j] != 0 and j < len(nums)-1:
    j += 1
    return j

    def Min_Not_Zero(i, nums):
    while nums == 0 and i < len(nums)-1:
    i += 1
    return i

    # Swap the first zero element with the first non-zero element which is latter than the first zero element
    def Swap_Zero(i=0, j=0, nums=[1, 2, 3, 4, 5, 0, 0, 0, 6, 0, 7, 0, 8, 0, 0, 9, 0, 0]):
    n = Min_Zero(j, nums)
    m = Min_Not_Zero(n, nums)
    if m < len(nums)-1 and n < len(nums)-1 and m > n:
    nums[m], nums[n] = nums[n], nums[m]
    Swap_Zero(m, n, nums = nums)
    return nums

    Swap_Zero()


    I've successfully run the code. It's verified.

    Continue reading...

Compartilhe esta Página