leetcode283. 移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

不过脑子做法

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        for i in range(n):
            if nums[i] == 0:
                nums.remove(nums[i])
                nums.append(0)

leetcode283. 移动零
方法二:
优化双指针

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

leetcode283. 移动零

上一篇:萌新web9


下一篇:Syntax Error: Error: PostCSS received undefined instead of CSS string