Leetcode篇:删除指定元素


@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)

猜你喜欢

转载自www.cnblogs.com/zzq-123456/p/9721290.html