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
  • 相关阅读:
    some tips
    ORA00847: MEMORY_TARGET/MEMORY_MAX_TARGET and LOCK_SGA cannot be set together
    Chapter 01Overview of Oracle 9i Database Perfomrmance Tuning
    Chapter 02Diagnostic and Tuning Tools
    变量与常用符号
    Chapter 18Tuning the Operating System
    标准输入输出
    Trace files
    DBADeveloped Tools
    Chapter 03Database Configuration and IO Issues
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5438250.html
Copyright © 2011-2022 走看看