天天看點

[LeetCode] Move Zeroes - 整數數組處理問題

目錄:

1.move zeroes  - 數組0移到末尾 [順序交換]

2.

題目概述:

given an arraynums, 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, givennums = [0, 1, 0, 3, 12], after calling your function,nums should be[1, 3, 12,

0, 0].

note:

        1.you must do this in-place without making a copy of the array.

        2.minimize the total number of operations.

解題方法:

題意是把數組nums中0的元素後置,同時不能采用指派數組。兩種方法:

        1.遇到是0的元素從數組最後向前存儲并移位,遇到非0元素從前存儲;

        2.推薦:從前往後查找,不是0的元素前移,并計算0的個數,後面的全置0。

我的代碼:

方法一:runtime: 28 ms

方法二:runtime: 8 ms

繼續閱讀