zoukankan      html  css  js  c++  java
  • 【leetcode】1441. Build an Array With Stack Operations

    题目如下:

    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. 

    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"]

    Constraints:

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

    解题思路:依次读取1~n之间的数字,如果数字等于target[0],那么只要做Push操作,同时删掉target[0];如果不相等,那么做Push和Pop操作。

    代码如下:

    class Solution(object):
        def buildArray(self, target, n):
            """
            :type target: List[int]
            :type n: int
            :rtype: List[str]
            """
            res = []
            for i in range(1,n+1):
                if len(target) == 0:
                    break
                if i == target[0]:
                    res.append("Push")
                    target.pop(0)
                else:
                    res.append("Push")
                    res.append("Pop")
    
            return res
  • 相关阅读:
    jquery实现奇偶行赋值不同css值
    Android短信批量插入速度优化的思考与尝试
    Android短信列表的时间显示
    短信优先级及有效期
    模拟器收短信和接电话的方法
    Android:Perferences的使用
    留个脚印
    Android电池电量更新 BatteryService(转)
    Android号码匹配位数修改
    CDMA SMS pdu解码
  • 原文地址:https://www.cnblogs.com/seyjs/p/13041209.html
Copyright © 2011-2022 走看看