Leetcode-Remove Element(Python)

1 Description(描述)

Given an array nums and a value val, remove all instances of that value in-place and return the new length.
給定一個數組數字和一個值val,刪除該值的所有實例並返回新的長度。

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
不要爲另一個數組分配額外的空間,只能通過修改輸入數組並且空間複雜度爲O(1)。

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.
函數應該返回length = 2,數字的前兩個元素是2。
It doesn’t matter what you leave beyond the returned length.
在返回的長度之外留下什麼並不重要。

Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
函數應該返回length = 5,數字的前5個元素包含0、1、3、0和4。
Note that the order of those five elements can be arbitrary.
注意,這五個元素的順序可以是任意的。
It doesn’t matter what values are set beyond the returned length.
在返回的長度之外設置什麼值並不重要。

2 Solution(解決方案)

方案一:遍歷列表比較每一個元素相同則刪除。

def removeElement(nums, val) :
        i = 0
        while i < len(nums):
            if nums[i] == val:
                nums.pop(i)
            else:
                i += 1
        return len(nums)

方案二:雙指針,一個指針負責遍歷數組,另一個負責指示新數組元素的位置,兩個指針所指元素相同則不考慮,不同就交換,指針增加一,最後返回指針。

def removeElement(nums, val) :
        i = 0
        for j in range(len(nums)):
            if nums[j] == val:
                continue
            else:
                nums[i] = nums[j]
                i += 1
        return i
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章