python--lintcode539. 移动零

描述

给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

1.必须在原数组上操作
2.最小化操作数

您在真实的面试中是否遇到过这个题?  

样例

给出 nums = [0, 1, 0, 3, 12], 调用函数之后, nums = [1, 3, 12, 0, 0].


基础题,没什么可说的,在python中比较简单:

class Solution:
    """
    @param nums: an integer array
    @return: nothing
    """
    def moveZeroes(self, nums):
        # write your code here
        i=0
        length=len(nums)
        while(i<len(nums)):
            if(nums[i]==0):
                del(nums[i])
                i=i-1
            i+=1
        for i in range(length-len(nums)):
            nums.append(0)
        return nums




s=Solution()
print(s.moveZeroes([1,2,3,0,4]))

猜你喜欢

转载自blog.csdn.net/wenqiwenqi123/article/details/80777891