在Python中删除元素
因此,如果输入类似于[0,1,5,5,3,0,4,5]5,则输出将为5。
为了解决这个问题,我们将遵循以下步骤-
计数:=0
对于数字的每个索引i
nums[count]:=nums[i]
如果nums[i]不等于val,则-
数:=数+1
返回计数
示例
让我们看下面的实现以更好地理解-
class Solution: def removeElement(self, nums, val): count = 0 for i in range(len(nums)): if nums[i] != val : nums[count] = nums[i] count +=1 return count ob = Solution()print(ob.removeElement([0,1,5,5,3,0,4,5], 5))
输入项
[0,1,5,5,3,0,4,5], 5
输出结果
5