在Python中删除元素

假设我们有一个数组num和另一个值val,我们必须就地删除该值的所有实例并找到新的长度。

因此,如果输入类似于[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

    以上是 在Python中删除元素 的全部内容, 来源链接: utcz.com/z/352491.html

    回到顶部