Problem Description
A stack with a special function is implemented, and on the basis of the basic functions of the stack, the operation of returning to the smallest element in the stack is realized.
There are three types of operations, op1 means push, op2 means pop, and op3 means getMin. You need to return an array with as many occurrences as op3, representing the answer to getMin each time
1<=Total number of operations<=1000000
-1000000<=Each operand<=1000000
Data guarantees that there are no illegal operations
Input description:
Input a two-dimensional array
Output description:
output a one-dimensional array (the smallest element of the current stack)
Example
Example 1
Enter
[[1,3],[1,2],[1,1],[3],[2],[3]]
Output
[1,2]
Solutions
analysis
- Solved by two stacks, one stack stores the elements pushed on the stack, and the other stack stores the smallest element of the elements pushed so far (the size is pushed on the stack in turn)
method
- Solved by two stacks, one stack stores the elements pushed on the stack, and the other stack stores the smallest element of the elements pushed so far (the size is pushed on the stack in turn)
Code
// 思路1
public class Solution {
public int[] getMinStack(int[][] op) {
// write code here
Stack<Integer> stack1 = new Stack<>(); // 记录完整的放入栈数据
Stack<Integer> stack2 = new Stack<>(); // 记录到目前放入为止的元素里最小的数字
List<Integer> list = new ArrayList<>();
for (int i = 0; i < op.length; i++) {
if (op[i][0] == 3) {
// 获取stack2栈顶的元素
list.add(stack2.peek());
} else if (op[i][0] == 2) {
// 弹出栈顶
int temp = stack1.pop();
// 如果弹出的元素是最小元素,stack2也弹出
if (temp == stack2.peek())
stack2.pop();
} else {
int temp = op[i][1];
// 压栈
stack1.push(temp);
// 如果压栈元素小于stack2的栈顶元素,则压栈
if (stack2.isEmpty() || temp <= stack2.peek())
stack2.push(temp);
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
Time complexity analysis:
O(M): Traverse the array
Space complexity analysis:
O(N): Two additional stacks are used, and the maximum storage of the stack is n.
If you want to test, you can go directly to the link of Niuke.com to do the test