代码随想录算法训练营第十一天| 逆波兰表达式求值 、滑动窗口最大值、前 K 个高频元素
逆波兰表达式求值
难点在于理解概念
/*
* @lc app=leetcode.cn id=150 lang=java
*
* [150] 逆波兰表达式求值
*/
// @lc code=start
import java.util.Stack;
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals("+")) {
int a = stack.pop();
int b = stack.pop();
stack.add(a+b);
} else if (tokens[i].equals("-")) {
int a = stack.pop();
int b = stack.pop();
stack.add(b-a);
} else if (tokens[i].equals("*")) {
int a = stack.pop();
int b = stack.pop();
stack.add(a*b);
} else if (tokens[i].equals("/")) {
int a = stack.pop();
int b = stack.pop();
stack.add(b/a);
} else {
stack.add(Integer.valueOf(tokens[i]).intValue());
}
System.out.println(stack.peek());
}
return stack.peek();
}
}
// @lc code=end
滑动窗口最大值
需要自己维护一个特殊的单调队列
前 K 个高频元素
只想到用hashmap存次数,但是没有想出用堆的方法来排序

浙公网安备 33010602011771号