283. Move Zeroes
两步: 1. 保持原顺序 2. 零在最后面
总体思路
先实现1后实现2,需要认识到如下之点
The 2 requirements of the question are:
Move all the 0's to the end of array.
All the non-zero elements must retain their original order.
It's good to realize here that both the requirements are mutually exclusive, i.e., you can solve the individual sub-problems and then combine them for the final solution.
很直观的方法,但有时也是非常好用的办法。
1 | class Solution { |
T(n) : O(n)
S(n) : O(n)
对上述方法优化空间占用
1 | class Solution { |
T(n) : O(n) S(n) : O(1)
再优化,由于上面需要执行完N次操作,还可以优化
1 | class Solution { |
T(n) : O(n)
S(n) : O(1)
这里仅需要执行非0的个数
由于noZeroIndex和num不同时,noZeroIndex指向的必定是0元素,这时与num进行交换就可以将0元素移动到后头,依次往复,所有的0都会跑到后面去
因为如果是0,noZeroIndex就不会加,就会留着,如果相同,那就是自己加自己。