一、前言

  题是上周五做的,开始思路有点问题,考虑不全,导致submit了3次才AC。

 

二、题283 Move Zeroes

  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.

  看到题目第一反应就是把非0项取出放入另一个list,再补全0,但是题目明确说了 without making a copy of the array,于是作罢。

 

三、解题思路

  取出0项对应list中的位置,从后往前删除0项,删一项补一项(补0),这样对应关系才不变。

  代码如下,runtime:88ms。

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        count=0
        tags=[]
        for num in nums:
            count+=1
            if num == 0:
                if str(count-1) not in tags:
                    tags.append(count-1)
        for tag in tags[::-1]:
            del nums[tag]
            nums.append(0)

  觉得这样不简洁,又看了下discuss里的优秀解法,也记录一下。

  把非0项从前往后放,在list后补0。runtime:80ms。

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        k=0 #step1:move all none zero numbers to the front
        for num in nums:
            if num!=0:
                nums[k]=num
                k+=1
        nums[k:]=[0]*(len(nums)-k) #step2: set the rest of the list to be zero

 

  

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-13
  • 2021-12-21
  • 2022-02-20
  • 2022-12-23
  • 2021-04-24
猜你喜欢
  • 2022-12-23
  • 2021-12-29
  • 2021-08-15
  • 2022-01-26
  • 2021-09-08
  • 2021-07-19
  • 2021-08-31
相关资源
相似解决方案