LeetCode #283 Move Zeroes
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.
Example:
Input: [0,1,0,3,12]
Output: [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
Use two pointers i
and j
. i
denotes to first zero position in list and j
is for iterating whole list. Once we found a none zero element in iteration, swap i
and j
, then move i
to next position.
Complexity
Obviously list will be iterated only once so it takes O(n) times with only O(1) extra space.