思路
简单模拟
由题意:target
数组中的数一定是递增的,且只包含1
到n
中的数字。
遍历数组target
,并利用一个变量cur
表示当前遍历到的1-n
中的数,如果:
cur < target[i]
,则将cur
压栈后马上出栈,即进行Push
和Pop
操作,并令cur++
,继续判断;cur == target[i]
,则只进行Push
操作,cur++
,i++
,开始遍历数组target
中下一个数cur > target[i]
,不会出现这种情况。因为前面两个操作始终会保证target[i] >= cur
,除非题目中存在无解的情况。
因此简单进行模拟即可,代码如下:
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
string push = "Push";
string pop = "Pop";
vector<string> ans;
int cur = 1;
for (const auto &num : target){
while (num != cur){
ans.push_back(push);
ans.push_back(pop);
cur++;
}
ans.push_back(push);
cur++;
}
return ans;
}
};