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 :
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]
Approach:
C++
#include <bits/stdc++.h>using namespace std;vector<string> buildArray(vector<int> &target, int n){vector<string> res;int max1 = target[target.size() - 1];for (int i = 1; i <= min(max1, n); i++){int j = 0;for (j = 0; j < target.size(); j++)if (target[j] == i){res.push_back("Push");break;}if (j == target.size()){res.push_back("Push");res.push_back("Pop");}}return res;}int main(){vector<int> target = {1, 3};int n = 3;vector<string> res = buildArray(target, n);cout << "[";for (int i = 0; i < res.size(); i++){cout << res[i];if (i != res.size() - 1)cout << ", ";}cout << "]";return 0;}
No comments:
Post a Comment