283_Move Zeroes
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.
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Example
Solution
Idea:
Use two pointers. Slow pointer indicates first zero location, fast pointer indicates first non-zero location.
Loop the fast pointer, and record the first available zero element in the array as the slow pointer. Swap the elements in the fast pointer and slow pointer when they are not the same.
All elements between the slow and faster pointer are zeroes.
Time Complexity:
Space Complexity:
Last updated