数组——移动零

2019-01-31  本文已影响0人  CoeusZ

题目

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

解题思路

思路一
遍历数组,如果遇到0,就原地更新数组,将原数组变成0以前+0以后+[0],同时将遍历索引值-1
结果,慢慢慢,至于为什么这么慢,可能是这种原地的更新方法虽然没有额外占内存,但是实际上操作步骤比较多吧....

思路二
遍历数组,如果遇到0,就删掉这个位置的元素,并把它扔到数组最后一位,同时索引值-1
结果快了一点些,可能这种一删一加的行为也相对耗时

别人最快的思路
定义index为0遍历数组,如果遇到不是0,就在数组的的index处更新该元素,并且index值加一
这样操作完了以后,就将整个数组中,原来的非0元素,全部放到了前面的位置,但这个时候,后面的位置,还会存在一些非0的元素。
所以遍历完成以后,在写一个while循环,将后面位置的元素全部用0补全。

答案(一)

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

答案(二)

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

答案(三)

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        index = 0
        for num in nums:
            if num != 0:
                nums[index] = num
                index = index + 1
        while(index < len(nums)):
            nums[index] = 0
            index = index + 1
上一篇 下一篇

猜你喜欢

热点阅读