天天看点

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学习心得