LeetCode 1441 Build an Array With Stack Operations (Python)

Posted by 小明MaxMing on May 10, 2020

题目

Given an array target and an integer n. In each iteration, you will read a number from list = {1,2,3…, n}.

Build the target array using the following operations:

  • Push: Read a new element from the beginning list, and push it in the array.
  • Pop: delete the last element of the array.
  • If the target array is already built, stop reading more elements.

You are guaranteed that the target array is strictly increasing, only containing numbers between 1 to n inclusive.

Return the operations to build the target array.

You are guaranteed that the answer is unique.

解题思路

遍历1到n中的每个数,如果这个数在target中出现,就加一个Push,否则加一个PushPop,如果target数组已经遍历完了,就退出循环

代码

class Solution:
    def buildArray(self, target, n: int):
        res = []
        p = 0
        for i in range(1, n + 1):
            if target[p] == i:
                res.append("Push")
                p += 1
            else:
                res.append("Push")
                res.append("Pop")
            if p == len(target):
                break
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅