• 283. Move 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.

    Example:

    Input: [0,1,0,3,12]
    Output: [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.

    要求不开额外数组内存,可以开两个变量,一个是统计0个个数,一个是当前数组不为0的位置到哪里了,每次不为零的数就往这个index移动,最后用统计出的0个个数往数组的最后补

    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: None Do not return anything, modify nums in-place instead.
            """
            zero_count = 0
            index = 0
            for i in range(len(nums)):
                if nums[i] == 0:
                    zero_count += 1
                else:
                    nums[index] = nums[i]
                    index += 1
            for i in range(index, index + zero_count, 1):
                nums[i] = 0
                
  • 相关阅读:
    python 爬虫 urllib模块 url编码处理
    python 爬虫 urllib模块 目录
    python 爬虫 urllib模块介绍
    python 爬虫 目录
    爬虫 介绍
    POJ 2533
    POJ 2531
    POJ 2524
    POJ 2505
    POJ 2521
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13223148.html
Copyright © 2020-2023  润新知