天天看點

LeetCode程式設計練習 - Move Zeroes學習心得

題目: 

   Given an array

nums

, write a function to move all

'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:

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

         2.Minimize the total number of operations.

   給定一個數組nums,編寫一個函數将所有0移動到它的末尾,同時保持非0元素的相對順序。必須在不需要複制數組的情況下進行操作。

思路:

     判斷數組中索引的元素為0時,将其與後面不為0的元素調換位置。使用輾轉相除法

LeetCode程式設計練習 - Move Zeroes學習心得