天天看點

移除元素—— python

問題描述

移除元素—— python

暴力求解代碼

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0
        while i < len(nums):
            if nums[i] == val:
                nums.pop(i)
            else :
                i = i + 1
        return len(nums)
           

結果

移除元素—— python

官方提供的雙指針法

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0
        j = 0
        while j < len(nums):
            if nums[j] != val:
                nums[i] = nums[j]
                i = i + 1
            j = j + 1
        return i
           

結果

移除元素—— python

竟然一樣?巧合!