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

  

时间: 2024-10-10 11:01:18

Leetcode刷题记录[python]——283 Move Zeroes的相关文章

Leetcode刷题记录[python]——344 Reverse String

一.前言 不是计算机专业出身,却有一颗程序猿的心. 昨日开始leetcode第一次刷题,选择了菜鸟方式,从AC率最高且难度为Easy的题开始,不管题是简单还是难,都想做个记录,既是方便以后回顾,又是以此作为一个激励,督促自己每天都能有所进步. 二.题344 Reverse String Write a function that takes a string as input and returns the string reversed. class Solution(object): def

Leetcode刷题记录[python]——349 Intersection of Two Arrays

一.前言 做了两题才慢慢摸清了leetcode的操作. 二.题349 Intersection of Two Arrays Given two arrays, write a function to compute their intersection. class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int]

Leetcode刷题记录[python]——258 Add Digits

一.前言 做这题有个小收获,关于Digital root的解法,有个极方便的小公式: 二.题258 Add Digits Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. class Solution(object): def addDigits(self, num): """ :type num: int :rtype: i

Leetcode刷题记录[python]——104 Maximum Depth of Binary Tree

一.前言 对于这类抽象问题还有self用法,还要多做多练习,此题是参考其他答案所做. 二.题104 Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # Definitio

Leetcode刷题记录[python]——561 Array Partition I

一.前言 二.题561 Array Partition I Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Inp

【leetcode刷题笔记】Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 题解:因为题目要求原地算法,所以我们只能利用矩阵第一行和第一列存放置零信息. 首先遍历第一行和第一列,看他们是否需要全部置零,用两个变量first_column_zero和first_row_zero来记录: 遍历矩阵,如果某个位置matrix[i][j]出现了0,就把matrix[i][0]和Matrix[0

leetcode刷题记录(2)

301. Remove Invalid Parentheses Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may contain letters other than the parentheses ( and ). Examples: "()())()&q

leetcode刷题记录(JAVA&Python)

---恢复内容开始--- --题目导航见页面左上角的悬浮框#目录导航#-- 相似题型: 1.1 twosum两数之和   2.2 3Sum三数之和 一.简单 1.1 twosum两数之和 原题: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 实例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 暴力解

leetcode刷题记录-Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that