1. 程式人生 > >Leetcode篇:刪除指定元素

Leetcode篇:刪除指定元素

num continue pycharm tin element lse etc 要求 on()


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

Leetcode篇:刪除指定元素