Problem
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]
.
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Solution 1 – 59ms
Go through the array. If ith
element is 0, then move all elements within [i+1,nums,length-1] one place ahead, and set the last element of the array to 0. To prevent endless loop when nums=[0,0,...,0]
, set a variable reapeatCount
.
|
|
Solution 2 – 19ms
Go through the array. If ith
element is 0, then find the first non-zero element within range [i+1,nums.length-1] and swap it with current element; if there is no such non-zero element, it means all non-zero elements are before zeroes – done! If current element is non-zero, just go on to the next.
|
|
Solution 2 is better than Solution 1. This is because in Solution 1, it is unnecessary to move all elements after a non-zero element one place ahead.
Written with StackEdit.