Python two pointer solution


  • 0
    R
    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            
            if not nums or len(nums) <= 1:
                return
            
            slow = 0;
            fast = 0;
            while(slow < len(nums) and fast < len(nums)):
                while(slow < len(nums) and nums[slow]!=0):
                    slow+=1
                
                if fast < slow:        
                    fast = slow
                
                while (fast < len(nums) and nums[fast]==0):
                    fast+=1
                if slow<len(nums) and fast < len(nums):
                    
                    temp = nums[slow]
                    nums[slow] = nums[fast]
                    nums[fast] = temp
                
                slow+=1
                fast+=1
                
    

Log in to reply
 

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