leetcode笔记--Move Zeroes

来源:互联网 发布:windows xp字体大小 编辑:程序博客网 时间:2024/06/01 10:45


Move Zeroes

题目:难度(Easy)

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.
Tags:Array,Two Pointers

分析:要求:就地更改数组,并且使得所有的操作最小

法1:就统计非0数的个数,缺点:可能遍历2遍数组,时间复杂度O(n)

代码实现:

class Solution(object):    def moveZeroes(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """               n = len(nums)        countOfNoZero = 0        for i in range(n):            if nums[i]:                nums[countOfNoZero] = nums[i]                countOfNoZero += 1        for i in range(countOfNoZero, n):            nums[i] = 0

法2:双指针,时间复杂度O(n)

代码实现:

class Solution(object):    #双指针       def moveZeroes(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        n = len(nums)        i, j = 0, 0#i指向第一个0,j指向第一个非0        while j < n and i<n:            while j<n and nums[j]==0:                j += 1            while i<n and nums[i]!=0:                i += 1            if j == n or i == n:                break            if j>i:#只有出现在第一个0的后面的非0数才需要移动,并占据第一个0 的位置                nums[i] = nums[j]                nums[j] = 0            else:#第一个非0数在第一个0的前面,不需要移动,则需要寻找下一个可能需要移动的非0数                j += 1


0 0
原创粉丝点击