今天是紀錄LeetCode解題的第二十七天
第二十七題題目:Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
給定一個整數陣列nums和一個整數 val,請就地(in-place)移除nums中所有等於val的元素,元素的順序可以改變,移除後不需要保持原本順序,最後回傳nums中不等於val的元素k個
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
for j in range(len(nums)):
if nums[j] != val:
nums[i] = nums[j]
i += 1
return i
初始狀態
第一次執行
第二次執行
第三次執行
第四次執行
最後回傳i(也就是2),表示前2個元素是已經移除掉和val相同的元素