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中, 根据索引数组批量移除数组元素大致有两种方法:
- 使用
pop
函数进行删除 需要对索引进行反转, 使其从后往前删除.pylis = ['🍌', '🍊', '🍐', '🍎'] index = [1, 2, 4] index_reverse = index.reverse() for i in index_reverse: lis.pop(i)
- 借助
enumerate
和列表推导式危险
这种方法会生成一个新的数组, 如果在函数内部使用的话, 不会修改外部的数组
pylis = ['🍌', '🍊', '🍐', '🍎'] index = [1, 2, 4] lis = [n for i, n in enumerate(lis) if i not in index]