目录
题目
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:
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.
解决方案
1 | public class Solution { |
注意事项
- 遍历一遍数组,遇到0,就给零值计数器加一。
- 遇到非零,如果前面至少有一个零(N>1),则将当前值前移N位,并给当前位赋值为0。