zoukankan      html  css  js  c++  java
  • 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"]
    class Solution {
        public List<String> buildArray(int[] target, int n) {
            List<String> res = new ArrayList();
            List<Integer> list = new ArrayList();
            for(int i: target) list.add(i);
            for(int i = 1; i <= n; i++){
                if(i > target[target.length - 1]) return res;
                if(list.indexOf(i) < 0){
                    res.add("Push");
                    res.add("Pop");
                }
                else {
                    res.add("Push");
                }
            }
            return res;
        }
    }

    多种方法,比如把target存到arraylist里面,然后遍历从1-n,当n比target最大的还大,就没有必要继续了,返回即可

    内循环中,如果target里面妹有n,就push再pop,否则push

  • 相关阅读:
    weka 学习
    支持向量机SVM
    U-Air:When Urban Air Quality Inference Meets Big Data--YuZheng
    城市计算与大数据
    python报错 IndentationError: unindent does not match any outer indentation level
    js 谈this
    js mouseover mouseout 多次触发
    sql语句分页多种方式ROW_NUMBER()OVER
    在GridView中设置每个单元格的数据
    OnRowDeleting事件和OnRowCommand事件之间的触发关系
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12866797.html
Copyright © 2011-2022 走看看