LeetCode 1441. Build an Array With Stack Operations
考点 | 难度 |
---|---|
Simulation | Easy |
题目
You are 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"
: Reads a new element from the beginning list, and pushes it in the array.
"Pop"
: Deletes the last element of the array.
If the target array is already built, stop reading more elements.
Return a list of the operations needed to build target. The test cases are generated so that the answer is unique.
思路
每个数都先push,如果这个数不在target
里,再pop。
答案
public List<String> buildArray(int[] target, int n) {
List<String> result = new ArrayList<>();
int j=0;
for (int i=1;i<=n && j<target.length;i++) {
result.add("Push");
if(target[j]==i) {
j++;
} else {
result.add("Pop");
}
}
return result;
}