代码随想录刷题day 11 | **150. 逆波兰表达式求值** **239. 滑动窗口最大值** **347.前 K 个高频元素**
[150. 逆波兰表达式求值](https://leetcode.cn/problems/reverse-string/)
使用栈即可,遍历token数组,遇到运算符就弹栈,取出两个数做运算然后压栈。遇到数字就压栈。最终栈中剩余的唯一数字就是结果。
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String s: tokens){
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
int num2 = stack.pop();
int num1 = stack.pop();
if(s.equals("+")) stack.push(num1 + num2);
if(s.equals("-")) stack.push(num1 - num2);
if(s.equals("*")) stack.push(num1 * num2);
if(s.equals("/")) stack.push(num1 / num2);
}else{
stack.push(Integer.parseInt(s));
}
}
return stack.peek();
}
}
239. 滑动窗口最大值
这里先给出Java中双端队列Deque的用法 https://blog.csdn.net/weixin_47772522/article/details/132342631
剩余的看注释即可
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
MyQueue queue = new MyQueue();
for(int i = 0; i < k; i++) queue.push(nums[i]);
int[] res = new int[nums.length - k + 1];
res[0] = queue.peek();
for(int i = 0; i < res.length - 1; i++){
queue.offer(nums[i]); //移除窗口左端的元素
queue.poll(nums[i+k]); //移入右端元素
res[i+1] = queue.peek();
}
return res;
}
}
class MyQueue{
Deque<Integer> queue;
public MyQueue(){
this.queue = new LinkedList<>();
}
public void offer(int x){ //在队列尾部插入元素(对于本题,插入窗口移动后最右端的元素) 命名尽量遵守队列的接口 offer/add代表添加元素 poll
while(this.queue.peekLast() != null && this.queue.peekLast() < x) this.queue.pollLast();
this.queue.offerLast(x);
}
public void poll(int x){ //在队列头删除元素,对于本题,意味着窗口向右挪动后,移除队列中对应于移出窗口的那个元素
if(this.queue.peekFirst() == x) this.queue.removeFirst();
}
public int peek(){
return this.queue.peekFirst();
}
}
347. 前 K 个高频元素
最主要的还是map的遍历以及优先队列的用法,这个和堆排序的思想很像。
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int num: nums){
map.put(num, map.getOrDefault(num, 0)+1);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((pair1, pair2)-> pair1[1] - pair2[1]); //前减后代表小顶堆
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
pq.offer(new int[]{entry.getKey(), entry.getValue()});
if(pq.size() > k) pq.poll();
}
int[] res = new int[k];
for(int i = k - 1; i >= 0; i--){
res[i] = pq.poll()[0];
}
return res;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步