Leetcode算法——27、数组删除元素

76 篇文章 1 订阅

给定一个数组和一个常量 val,删除数组中所有等于 val 的元素,返回新的长度。

备注:

  • 不要为另外的数组去开辟新的空间,只能修改原数组,空间复杂度为O(1)。
  • 元素的顺序可以改变。
  • 数组在返回长度之后的元素无关紧要。

示例:
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn’t matter what you leave beyond the returned length.

Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn’t matter what values are set beyond the returned length.

思路

可以参考数组去重,里面的两个去重方法都适用于本题。

本题以不改变数组长度的第二种方法进行实现:

1、从左到右扫描,维护一个索引,这个索引始终保持为新数组的最后一位。
2、如果扫描到了一个元素不等于val,则将索引+1,且索引对应的值修改为当前元素值。
3、此方法不会改变数组的长度。

python 实现

def removeElement(nums, val):
    """
    :type nums: List[int]
    :type val: int
    :rtype: int
    """
    if not nums:
        return 0
    
    idx = 0
    for num in nums:
        if num != val:
            nums[idx] = num
            idx += 1
    return idx

if '__main__' == __name__:
    nums = [0,1,2,2,3,0,4,2]
    val = 2
    print(removeElement(nums, val))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值