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.
這題和 Remove Element 類似
但不同的點在於,必須保持原本的順序
解題想法如下
- 先將所有非零的數,一個一個從前面按順序排好
- 剩餘的位置,全部都填 0
Java
或者直接swap 也是可以
kotlin
沒有留言:
張貼留言