Python insert() / append() 用法 Leetcode实战演示

本文通过实例解析Python中insert和append方法在LeetCode 1389问题中的应用,讲解如何根据给定的数值数组和索引构造目标数组。通过代码演示,理解如何在队列操作中灵活使用这两种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python insert / append Leetcode实战

简单理解就是:
append()是和朋友一起在队尾依次排队
insert(index, object)就是你朋友已经在队列里了,你插队到你朋友的位置–> insert(‘你朋友的位置’, ‘你自己’)
以一道Leetcode例题演示Python中Insert和append的用法。

#好朋友B帮你占了位置,你站到了B前面
You = 'You'
Queue = ['A','B','C','D']
Queue.insert(1,You)
print(Queue)
#['A', 'You', 'B', 'C', 'D']

原题(Leetcode1389)

给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组:

目标数组 target 最初为空。
按从左到右的顺序依次读取 nums[i] 和 index[i],在 target 数组中的下标 index[i] 处插入值 nums[i] 。
重复上一步,直到在 nums 和 index 中都没有要读取的元素。
请你返回目标数组。

题目保证数字插入位置总是存在。

详细解法

class Solution:
    def createTargetArray(self, nums, index):
        res = [nums[0]]
        for i in range(1,len(index)):
            if index[i] > len(res)-1:
            #若index位置比当前队列长度还长,那理应排在后面,直接append队尾添加
                res.append(nums[i])
                print('---------append----------')
                print('append:',index[i],nums[i])
                print(res)
            else:
            #若index位置处于当前队列中间,则执行insert插队。
                res.insert(index[i],nums[i])
                print('---------insert----------')
                print('insert',index[i],nums[i])
                print(res)
        return res
            
x = Solution()
x = x.createTargetArray([5,3,3,5,1],[0,0,2,1,2])
print(x)

结果演示:
num: [5,3,3,5,1]
index: [0,0,2,1,2]

res= [5]
---------insert----------
insert 0 3
[3, 5]
---------append----------
append: 2 3
[3, 5, 3]
---------insert----------
insert 1 5
[3, 5, 5, 3]
---------insert----------
insert 2 1
[3, 5, 1, 5, 3]
[3, 5, 1, 5, 3]

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纯人工不智能

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值