Skip to content

Move Zeroes

andyaganrun edited this page Jul 9, 2017 · 1 revision

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

java public void moveZeroes(int[] nums) { if (nums == null || nums.length == 0) return;

int insertPos = 0;
for (int num: nums) {
    if (num != 0) nums[insertPos++] = num;
}        

while (insertPos < nums.length) {
    nums[insertPos++] = 0;
}

}

Python3:

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

Clone this wiki locally