zoukankan      html  css  js  c++  java
  • Leetcode刷题记录[python]——283 Move Zeroes

    一、前言

      题是上周五做的,开始思路有点问题,考虑不全,导致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

      

  • 相关阅读:
    composer使用git作为仓储
    monolog记录日志
    lumen laravel response对象返回数据
    lumen中间件 Middleware
    AcWing 901. 滑雪
    leetcode 34. 在排序数组中查找元素的第一个和最后一个位置
    acwing 902. 最短编辑距离
    ACWING 844. 走迷宫
    leetcode 5199. 交换字符串中的元素
    AcWing 836. 合并集合
  • 原文地址:https://www.cnblogs.com/Myoungs/p/5520397.html
Copyright © 2011-2022 走看看