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.
要求不改變順訊,明顯地,不能使用兩根指針進行交換,交換會破壞順序。
很明顯的一種想法是求出零的個數,再逐個把非零的數搬到合法的索引上,但是這樣是兩次遍歷,而且是沒有必要的。
只需要一次遍歷就可以了,維護一根指針,作為非零元素的索引,當i掃描到末尾時,這個索引應該在第一個零的位置。
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.