[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:
- You must do this in-place without making a copy of the array.
- 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])