题目描述
给你一个数组 target 和一个整数 n。每次迭代,需要从 list = { 1 , 2 , 3 ..., n } 中依次读取一个数字。
请使用下述操作来构建目标数组 target :
"Push":从 list 中读取一个新元素, 并将其推入数组中。
"Pop":删除数组中的最后一个元素。
如果目标数组构建完成,就停止读取更多元素。
题目数据保证目标数组严格递增,并且只包含 1 到 n 之间的数字。
请返回构建目标数组所用的操作序列。如果存在多个可行方案,返回任一即可。
示例 1:
输入:target = [1,3], n = 3
输出:["Push","Push","Pop","Push"]
解释:
读取 1 并自动推入数组 -> [1]
读取 2 并自动推入数组,然后删除它 -> [1]
读取 3 并自动推入数组 -> [1,3]
示例 2:
输入:target = [1,2,3], n = 3
输出:["Push","Push","Push"]
示例 3:
输入:target = [1,2], n = 4
输出:["Push","Push"]
解释:只需要读取前 2 个数字就可以停止。
提示:
1 <= target.length <= 100
1 <= n <= 100
1 <= target[i] <= n
target 严格递增
题目思路
- 这是一道模拟的题目,判断俩个位置的值,如果这俩个位置的值想差为1,好的,直接push当前位置的值,当时如果当前俩个位置的值相差不是1,那么通过俩个位置对应的值计算循环几遍,每执行一遍,也就是没循环一次,集合中添加push,pop的操作,每次结束后都需要更新之前一个位置的值。
- 起初我错误的思路:也是判断俩个位置的值,当时考虑的稍微有点问题,通过比较cur,next位置的值,具体处理的逻辑有点问题,后来修正了一下,正确了!!!
实现代码
自己实现代码
class Solution {
public List<String> buildArray(int[] target, int n) {
List<String> res=new ArrayList<>();
int temp=0,next=0;
for(int i=0;i<target.length-1;i++){
temp=target[i];
next=target[i+1];
if(i==0&&temp!=1){
int cnt=temp-1;
while(cnt-->0){
res.add("Push");
res.add("Pop");
}
}
if(temp+1==next){
res.add("Push");
}else{
res.add("Push");
int cnt=next-temp-1;
while(cnt-->0){
res.add("Push");
res.add("Pop");
}
}
}
res.add("Push");
return res;
}
}
运行结果:
参考官方代码
class Solution {
public List<String> buildArray(int[] target, int n) {
List<String> res=new ArrayList<>();
int pre=0;
for(int i=0;i<target.length;i++){
int temp=target[i];
for(int j=0;j<temp-pre-1;j++){
res.add("Push");
res.add("Pop");
}
res.add("Push");
pre=temp;
}
return res;
}
}