• leetcode笔记9 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.

    my answer:

     重点知识:

    (1) list.remove(obj) , obj指要移除的元素

    (2) list 添加元素的方法,转自 http://www.linuxde.net/2013/02/12497.html

    List 是 Python 中常用的数据类型,它一个有序集合,即其中的元素始终保持着初始时的定义的顺序(除非你对它们进行排序或其他修改操作)。
    在Python中,向List添加元素,方法有如下4种方法(append(),extend(),insert(), +加号)

    1. append() 追加单个元素到List的尾部,只接受一个参数,参数可以是任何数据类型,被追加的元素在List中保持着原结构类型。此元素如果是一个list,那么这个list将作为一个整体进行追加,注意append()和extend()的区别。

    >>> list1=['a','b']
    >>> list1.append('c')
    >>> list1
    ['a', 'b', 'c']

    2. extend() 将一个列表中每个元素分别添加到另一个列表中,只接受一个参数;extend()相当于是将list B 连接到list A上。

    >>> list1
    ['a', 'b', 'c']
    >>> list1.extend('d')
    >>> list1
    ['a', 'b', 'c', 'd']

    3. insert() 将一个元素插入到列表中,但其参数有两个(如insert(1,”g”)),第一个参数是索引点,即插入的位置,第二个参数是插入的元素。

    >>> list1
    ['a', 'b', 'c', 'd']
    >>> list1.insert(1,'x')
    >>> list1
    ['a', 'x', 'b', 'c', 'd']

    4. + 加号,将两个list相加,会返回到一个新的list对象,注意与前三种的区别。前面三种方法(append, extend, insert)可对列表增加元素的操作,他们没有返回值,是直接修改了原数据对象。 注意:将两个list相加,需要创建新的list对象,从而需要消耗额外的内存,特别是当list较大时,尽量不要使用“+”来添加list,而应该尽可能使用List的append()方法。

    >>> list1
    ['a', 'x', 'b', 'c', 'd']
    >>> list2=['y','z']
    >>> list3=list1+list2
    >>> list3
    ['a', 'x', 'b', 'c', 'd', 'y', 'z']

    这个函数性能不是很高,积极寻找其他方法

  • 相关阅读:
    pause函数
    内核实现信号捕捉原理
    sigaction()函数
    SSIS使用事务回滚
    Sql Server XML
    Powershell远程执行命令
    光盘yum源搭建
    挂载光盘
    网络管理
    用户管理
  • 原文地址:https://www.cnblogs.com/qicaide/p/6020375.html
Copyright © 2020-2023  润新知