leetcode 27. Remove element

Remove element

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

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

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

在这里插入图片描述

重点:不分配附加的空间给另外一个array,需要通过modifying the input array in-place with O(1) extra memory.

双指针法

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        l,r=0,len(nums)-1
        if len(nums)==0:
            return 0

        while l<r:
        
            while (l<r and nums[l]!=val):
                l+=1
            while (l<r and nums[r]==val):
                r-=1
        
            nums[l],nums[r]=nums[r],nums[l]

        return l if nums[l]==val else l+1

记录
(1)双指针法,设定两个指针,一个从左往右移动,如果遇到第一个val,就停止,另外一个指针从右开始往左移动,遇到第一个不是val的就停止。然后两个元素交换。
(2)移动到两个指针到一起后停止。

我犯的错误
(1)while的条件确定,在里面的while也需要有l<r这项,我把这项弄错了,所以结果一直不对。如果没有这个,也许会导致l>r,就出错了。
(2)细节部分,比如r的初始值是len(nums)-1而不是len(nums)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值