每日一算法:[LeetCode]5. Move Zeros移动0到数组末尾

[LeetCode]5. Move Zeros移动0到数组末尾

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.

解法:注意非零元素移到数组前面后的顺序与原来的相对顺序不能改变,并且不能另外开辟临时数组。思路:(1)设置两个游标:index1=0, index2=0;(2)从头往后扫描,若当前元素非零,则index1++,直至找到数组中第一个零元素;(3)设置index2=index1+1,从此处继续往后扫描,若当前元素为0,则index2++,直至找到第一个零元素后的第一个非零元素;(4)交换这两个元素swap(arr[index1], arr[index2]);(5)index1++,重复步骤(2)(3)(4),直至index1或者index2超出数组长度。时间复杂度O(n)。

 

import time
from functools import wraps
def time_this_function(func):
    #作为装饰器使用,返回函数执行需要花费的时间
    @wraps(func)
    def wrapper(*args,**kwargs):
        start=time.time()
        result=func(*args,**kwargs)
        end=time.time()
        print(func.__name__,end-start)
        return result
    return wrapper
@time_this_function
def moveZeroes(nums):
    l = len(nums)
    i, j = 0, 0
    while i < l:
        if nums[i] == 0:
            j = i + 1
            while j < l:
                if nums[j] != 0:
                    temp = nums[i]
                    nums[i] = nums[j]
                    nums[j] = temp
                    break
                j += 1
            if j >= l:
                break
        i += 1
    print(nums)
moveZeroes([0,1,0,0,0,22,2,2,2,2,2,4,0,8,7,9,1,0,0,0,0,2,1,1,2,2,2,2,3,33,0,3,3,3,2,3])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值