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.
我的做法:
从最后一个obj开始扫描,发现0,就remove,然后再append。
一开始的错误:
从第一个开始扫描,因为用的是range循环,这样i会受影响,结果改了很多,最后发现从最后一个开始就好。
缺点:
比较慢。
改进:
看到做得最快的人的做法是,使用了两次循环。
第一次循环把所有非0的数覆盖,然后第二次循环把末尾的数改为0。 使用的是nums[-i-1]=0这种方法。