1441. Build an Array With Stack Operations

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.

C++解法

class Solution {
public:
    vector<string> buildArray(vector<int>& target, int n) {
        vector<int> inputArray(n);
        vector<string> result;
        int j=1;
        for(int i=0;i<target.size();){
            if(target[i]==j){
                j++;
                i++;
                result.push_back("Push");
            }else{
                j++;
                result.push_back("Push");
                result.push_back("Pop");
            }
        }
        return result;
    }
};

Java解法

class Solution {
    public List<String> buildArray(int[] target, int n) {
        List<String> result=new ArrayList<String>();
        for(int i=0,j=1;i<target.length;){
            if(target[i]==j){
                i++;
                j++;
                result.add(new String("Push"));
            }else{
                j++;
                result.add(new String("Push"));
                result.add(new String("Pop"));
                
            }
        }
        return result;
    }
}

Go解法

func buildArray(target []int, n int) []string {
    result := []string{}
    j:=1
    for i:=0;i<len(target); {
        if target[i]==j {
            i++
            j++
            result = append(result,"Push")
        }else {
            j++
            result = append(result,"Push","Pop")
        }
    }
    return result
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值