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

 

转载于:https://www.cnblogs.com/sherylwang/p/5438250.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值