leetcode 27 题解 翻译 Python版

27. 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 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.

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.

题目翻译

给定一个数组和一个值,就地删除数组中和该值相同的所有元素并返回新的长度。

不要创建其他数组分配额外的空间,你必须通过O(1)空间复杂度就地修改输入数组来实现这一点。

元素的顺序可以改变。只要返回了新的长度,数组中是否存在超过这个索引的元素无所谓(即数组中高索引元素可以不删除)。

示例1:

给定的数组 = [3,2,2,3], 值 = 3,
你的函数应该返回长度=2,数组修改后前两个元素为2

解题方案

标签: Two Pointers

思路:

  • 本题需要维护两个数组指针i和j,从数组0元素遍历至数组最后一个元素。若在数组中发现和给的val值相同的元素,则将数组后面和val值不同的元素前移覆盖这个元素。

  • 算法复杂度O(n)。

代码:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0
        j = 0
        while j < len(nums):
            if nums[j] == val:  # 数组内的值和要删除的元素值相同
                j += 1
            else:
                if i != j:  # 将数组后边和所给元素不相同的元素前移
                    nums[i] = nums[j]
                i += 1
                j += 1
        del nums[i:len(nums)]  # 删除多余元素
        return len(nums)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值