[抄题]:
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.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
不知道怎么就地操作
[一句话思路]:
用一个指针来控制,就能实现就地操作
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 没有理解:0是while最后一起添加的
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
全是0可以最后一起添加
[复杂度]:Time complexity: O(n) Space complexity: O(1)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
单个指针,实现就地
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
27. Remove Element
[代码风格] :
class Solution { public void moveZeroes(int[] nums) { //cc if (nums == null || nums.length == 0) return; //ini int insertPos = 0; for (int num : nums) { //no 0s if (num != 0) { nums[insertPos++] = num; } } //0s while (insertPos < nums.length) { nums[insertPos++] = 0; } //return }}