LeetCode--Move Zeroes(移动0元素)Python

题目:

给定一个数组。将数组中的0移动到数组末尾,其他元素保持原有的顺序,直接对原数组进行操作,不用返回

解题思路:

对数组遍历,使用flag来标记当前数组内容为0的位置,若遍历到nums[i]的值为非0元素,则将其移动到之前为0的元素位置,并将遍历到的位置赋0.

代码(Python):

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        flag = []
        for i in range(len(nums)):
            if nums[i]==0:
                flag.append(i)
            elif nums[i]!=0 and flag!=[]:
                nums[flag[0]] = nums[i]
                nums[i] = 0
                flag.append(i)
                flag.pop(0)
            else:
                continue

你可能感兴趣的:(LeetCode)