leetcode 1441. Build an Array With Stack Operations(python)

397 阅读1分钟

描述

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.

Return the operations to build the target array. You are guaranteed that the answer is unique.

Example 1:

Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: 
Read number 1 and automatically push in the array -> [1]
Read number 2 and automatically push in the array then Pop it -> [1]
Read number 3 and automatically push in the array -> [1,3]	

Example 2:

Input: target = [1,2,3], n = 3
Output: ["Push","Push","Push"]

Example 3:

Input: target = [1,2], n = 4
Output: ["Push","Push"]
Explanation: You only need to read the first 2 numbers and stop.

Example 4:

Input: target = [2,3,4], n = 4
Output: ["Push","Pop","Push","Push","Push"]

Note:

  • 1 <= target.length <= 100
  • 1 <= target[i] <= n
  • 1 <= n <= 100
  • target is strictly increasing.

解析

根据题意,因为 target 是升序的,所以只要遍历 [1,target[-1]+1] 的所有元素,只要每个元素在 target 中存在,就在 res 中添加 Push,如果不存在就添加 Push 和 Pop ,遍历结束得到的就是答案。

解答

class Solution(object):
    def buildArray(self, target, n):
        """
        :type target: List[int]
        :type n: int
        :rtype: List[str]
        """
        ans = []
        for i in range(1,target[-1]+1):
            if i in target:
                ans.append("Push")
            else:
                ans.append("Push")
                ans.append("Pop")
        return ans
        	      
		

运行结果

Runtime: 20 ms, faster than 69.23% of Python online submissions for Build an Array With Stack Operations.
Memory Usage: 13.2 MB, less than 93.27% of Python online submissions for Build an Array With Stack Operations.

原题链接:leetcode.com/problems/bu…

您的支持是我最大的动力