import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param op string字符串一维数组
* @param vals int整型二维数组
* @return int整型一维数组
*/
public int[] max_weight_cow (String[] op, int[][] vals) {
// write code here
int[] ans = new int[op.length];
Stack<Integer> stack = new Stack<>();
Queue<Integer> q = new PriorityQueue<>((o1, o2) -> o2 - o1);
for (int i = 0; i < op.length; i++) {
if ("MaxCowStack".equals(op[i])) ans[i] = -1;
else if ("push".equals(op[i])) {
ans[i] = -1;
stack.push(vals[i][1]);
q.offer(vals[i][1]);
} else if ("pop".equals(op[i])) {
ans[i] = -1;
q.remove(stack.pop());
} else if ("top".equals(op[i])) {
ans[i] = stack.peek();
} else if ("getMax".equals(op[i])) {
ans[i] = q.peek();
}
}
return ans;
}
}
- 利用两个Java提供的数据结构:栈和优先队列
- 栈 Stack 用于完成一系列的操作(push、pop、top)
- 优先队列 PriorityQueue 使用大顶推用于维护最大值,对应获取最大值的操作(getMax)
- 相关操作的处理:
- push:入栈、入队列
- pop:出栈、队列删除出栈元素
- top:查看栈顶元素
- getMax:查看大顶堆堆顶元素
- 输出结果存储在 ans 数组中。