Move Zeroes
Given an arraynums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Analysis
Two Pointers两个指针
i - slow pointer, 需要被替换写入的index,当前元素为0,可以看成insert position
j - fast pointer, 下一个非0元素,将被换到i的位置
这个方法可以避免许多0元素时不必要的swap操作,比如
第一个循环中,j就会找到第一个非0元素,这里是nums[5] = 1;
i会找到第一个需要被替换的0元素位置,这里是nums[0] = 0;
Solution
Two Pointers - Fast & Slow
Insert Index - Swap (LeetCode Official Solution)
the code will maintain the following invariant:
All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.
All elements between the current and slow pointer are zeroes.
Therefore, when we encounter a non-zero element, we need to swap elements pointed by current and slow pointer, then advance both pointers. If it's zero element, we just advance current pointer.
Complexity:
O(n) time
O(1) space
Ref
https://leetcode.com/problems/move-zeroes/discuss/72000/1ms-Java-solution/74551
Reference
Last updated