首页 > 解决方案 > 有什么办法可以避免“在第一个空索引处插入”?

问题描述

我正在使用 Python3,我想使用 insert() 函数在特定索引处插入 Int。我知道该函数将首先尝试将其插入到我指定索引之前的第一个空索引处。有没有办法避免这种行为并首先插入我指定的索引?尝试执行以下操作:

[18, 6, 6, 6, 1, -1]

但实际结果如下:

[18, -1, 6, 1, 6, 6]
def replaceElements(self, arr: List[int]) -> List[int]:
        res = []
        temp = -1
        for index in range(len(arr)-1, -1, -1):
            res.insert(index, temp)
            if arr[index] > temp:
                temp = arr[index]
        return res

标签: pythonpython-3.x

解决方案


推荐阅读