Leetcode题库——27.移除元素


@author: ZZQ
@software: PyCharm
@file: removeElement.py
@time: 2018/9/23 14:04
要求:给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
e.g.:
1) 给定 nums = [3,2,2,3], val = 3,
函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
2) 给定 nums = [0,1,2,2,3,0,4,2], val = 2,
函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。

class Solution():
    def __init__(self):
        pass

    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if not nums:
            return 0
        location = 0
        new_len = len(nums)
        for i in range(len(nums)):
            if nums[i] == val:
                new_len -= 1
                continue
            else:
                nums[location] = nums[i]
                location += 1
        return new_len


if __name__ == "__main__":
    answer = Solution()
    nums = [3,2,2,3]
    print(answer.removeElement(nums=nums, val=4))
    print(nums)

转载于:https://www.cnblogs.com/zzq-123456/p/9721290.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值