zoukankan      html  css  js  c++  java
  • Remove Element

    Given an array and a value, remove all instances of that value in place and return the new length.

    Do not allocate extra space for another array, you must do this in place with constant memory.

    The order of elements can be changed. It doesn't matter what you leave beyond the new length.

    Example:
    Given input array nums = [3,2,2,3]val = 3

    Your function should return length = 2, with the first two elements of nums being 2.

    这题要求从已知数组中查找某个元素,要求in  place 删除该元素,并返回新序列的长度,题目提示新长度之后的数组中的内容不用考虑。

    数组要求in place删除元素,很容易想起来从最右端开始删除。具体在这题的思路是维护双指针,指针p1从头开始移动,指针p2从尾开始移动。

    (1) A[p1]=value时,A[p1] = A[p2], p2--,但不能p1++,因为也可能A[right]=value
    (2) A[p1]!=value时,left++
    注意在循环结束时,p2指向的当前元素及其之前元素的值都不等于val,为合格元素,所以返回的长度为p2+1。
    该算法从前往后扫了一遍,时间复杂度为O(n),空间复杂度为O(1).值得注意的是,一些算法使用了list.remove,其本身复杂度为O(n),但是这样的时间复杂度为O(n^2). 另外算法从后面取值填充前面空位,比在前面取值赋值的赋值次数要少很多。
    if not nums:
                return 0
            p1 = 0
            p2 = len(nums)-1
            ret = 0
            while p1<=p2:
                if nums[p1]!=val:
                    p1 += 1
                else:
                    nums[p1]=nums[p2]
                    p2 -=1
            return p2+1
  • 相关阅读:
    bit byte哪些事
    各种字符集和编码详解
    常用工具大全
    表单提交的3种方式,http post的contentType
    主动发电
    Hibernate与 MyBatis的比较
    storm简介
    2013年十大免费云空间排行榜-给开发者建站用的免费云主机
    中国著名讲师全录
    iptables只允许指定ip地址访问指定端口
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5438250.html
Copyright © 2011-2022 走看看