Very simple python solutions


  • 13
    G

    Solution 1: traverse and swap last 0 and last non 0

    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            last0 = 0
            for i in range(0,len(nums)):
                if (nums[i]!=0):
                    nums[i],nums[last0] = nums[last0],nums[i]
                    last0+=1
    

    Solution 2 : one-liner from @toontong: use sort() with customized compare function

    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            nums.sort(cmp=lambda a,b: 0 if b else -1)

  • 0
    P

    This is simple but seems to have redundant operations.
    Ex: nums = [1, 2, 3] then the line next to the last line will be always executed.


  • 0
    G

    yep, in your Ex, it will keep swap elements with itself. we can add one more "if (last! = i)" to prevent that, but I'm not sure which one will be quicker. maybe compiler will just ignore something like (a[i] = a[i])


  • 0
    T

    nums.sort(cmp= lambda a, b: -1 if b == 0 else 0)


  • 0
    G

    this one is cool


  • 3
    J

    Mine's pretty simple and very readable.

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

  • 0
    G

    looks simple but I think we should avoid use pop(n) because it's not efficient


  • 9
    E

    My python code is simple:

    def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            for i in range(0,nums.count(0)):
                nums.remove(0)
                nums.append(0)

  • 0
    P

    may i ask how to understand this syntax?
    nums.sort(cmp= lambda a, b: -1 if b == 0 else 0)


  • 0
    C

    @eddiewu6 said in Very simple python solutions:

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

    Why is the range until nums.count(0)?


  • 0
    E

    @cdmusic80 said in Very simple python solutions:

    @eddiewu6 said in Very simple python solutions:

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

    Why is the range until nums.count(0)?

    num.count(0) returns the total count of 0 in the list nums. For example is the list is like [1,2,3,0,5,0], num.count(0) returns 2(There are 2 '0' in the list.)


Log in to reply
 

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