leetcode with python:283. Move Zeroes

题目:

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

给定一个阵列,将0移到阵列最后,其余非0元素维持原来的顺序
且不能使用新的阵列来进行操作
ex:input:[0,1,0,3,12]=>output:[1,3,12,0,0]

我用两个指标一个代表0的位置,一个代表非0元素的位置来实作

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

两个指标,i专门走0,j专门走非0
如果j位置>i位置且j的位置非0,两者的元素互换
i跑到下一个0,其余状况就是j继续往前走
j遍历完后我们要的阵列也形成了
最后执行时间187ms(faster than 83.39%)

但在看讨论区时我才发现,"将0移到阵列后"不就等于"将非0元素移到阵列前"吗
我居然没有想到,所以操作其实可以不像上面那样繁杂

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

一个指标pos表下次存放位置,一个指标i开始搜寻非0元素
i开始遍历,一遇到非0元素就和pos的元素互换
pos前往下一个位置
i遍历完后就达成把所有非0元素顺序不变的往前移了
最后执行时间161ms(faster than 98.76%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章