Skip to content

27.移除元素

题目链接

https://leetcode.cn/problems/remove-element

解题思路

下标移除

下标移除法在第26题的字典法中也碰到过. 思路非常简单, 就是找到所有与val元素相等的元素的下标, 将其保存在一个index数组中, 然后对这个index数组进行倒序排序, 目的是为了首先pop掉下标大的元素, 避免对前面元素和其下标的对应关系造成影响.

py
# ⌚ 44ms 📀 16.4MB
class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        length = len(nums)
        k = length
        index = []
        for ind in range(length):
            if nums[ind] == val:
                index.append(ind)
                k -= 1
        for ind in sorted(index, reverse=True):
            nums.pop(ind)
        return k

提示

在Python中, 根据索引数组批量移除数组元素大致有两种方法:

  1. 使用pop函数进行删除 需要对索引进行反转, 使其从后往前删除.
    py
    lis = ['🍌', '🍊', '🍐', '🍎']
    index = [1, 2, 4]
    index_reverse = index.reverse()
    for i in index_reverse:
        lis.pop(i)
  2. 借助enumerate和列表推导式

    危险

    这种方法会生成一个新的数组, 如果在函数内部使用的话, 不会修改外部的数组

    py
    lis = ['🍌', '🍊', '🍐', '🍎']
    index = [1, 2, 4]
    lis = [n for i, n in enumerate(lis) if i not in index]

采用 CC BY-NC 4.0 许可证发布