Leetcode: Move Zeroes

题目如下:

283Move Zeroes

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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


代码如下:

class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        l=len(nums)
        moveindex=0
        for i in range (l):
            if (nums[i]!=0):
                nums[moveindex],nums[i] = nums[i],nums[moveindex]
                moveindex=moveindex+1


分析如下:

先声明一个index变量来存放下一个非零数字的位置,初始值为0。

遍历队列,每找到一个非零的数,就将他与nums[index]的值进行交换,并让index自家。

最后将所有非零数字都放到了数组的前半部分。


结果如下:



猜你喜欢

转载自blog.csdn.net/qq_41794348/article/details/80150117
今日推荐