27.移除元素
解法一:对于整数顺序表nums,删除其中所有x元素后得到的结果顺序表可以和原nums共享,所以求解问题转化成新建结果顺序表
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for i in range(len(nums)):
if nums[i] != val:
nums[k] = nums[i]
k += 1
nums = nums[:k]
return k
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for i in range(len(nums)):
if nums[i] == val:
k += 1
else:
nums[i-k] = nums[i]
m = len(nums)-k
nums = nums[:m]
return m