Move Zeros python


  • 0
    M

    My solution is like this:

    count = nums.count(0)

    if count != len(nums) and count != 0:

    for i in nums:
        if i == 0: nums.remove(i)
    for i in range(count):
        nums.append(0)
    

    leetcode returns an error like this:

    input:[1,0,0]
    yours: [1,0,0,0]
    expected: [1,0,0]

    Why this happened and how to solve it?? Thx a lot


  • 1
    J

    I just solved it, here's my solution.

    for n in range(len(nums)-1,-1,-1):
    if(nums[n] == 0):
    nums.append(nums.pop(n))


  • 0
    M

    Thx~ It works well and beats 70% of the answers.


  • 0
    M

    Well , I m guilty of this too . but do you guys think we can use the inbuilt functions remove & append ?


  • 0
    U

    In fact your answer is a bit different that what is asked. The question asks 'in place' change for the list. I assume the answer shall only modify value of list items, not the list itself.


Log in to reply
 

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