一、 逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack=new LinkedList();
for(String s:tokens){
if("+".equals(s)){
stack.push(stack.pop()+stack.pop());
}else if("-".equals(s)){
stack.push(-stack.pop()+stack.pop());
}else if("*".equals(s)){
stack.push(stack.pop()*stack.pop());
}
else if("/".equals(s)){
int temp1=stack.pop();
int temp2=stack.pop();
stack.push(temp2/temp1);
}else {
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}
二、滑动窗口最大值
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
ArrayDeque<Integer> deque=new ArrayDeque<>();
int n=nums.length;
int[] res=new int[n-k+1];
int index=0;
for(int i=0;i<n;i++){
while(!deque.isEmpty()&& deque.peek()<i-k+1){
deque.poll();
}
while(!deque.isEmpty()&& nums[deque.peekLast()]<nums[i]){
deque.pollLast();
}
deque.offer(i);
if(i>=k-1){
res[index++]=nums[deque.peek()];
}
}
return res;
}
}
三、前 K 个高频元素
class Solution {
public int[] topKFrequent(int[] nums, int k) {
PriorityQueue<int[]> pq=new PriorityQueue<>((o1,o2)->o1[1]-o2[1]);
int[] res=new int[k];
Map<Integer,Integer> map=new HashMap<>();
for(int num:nums)
map.put(num,map.getOrDefault(num,0)+1);
for(var x:map.entrySet()){
int[] tmp=new int[2];
tmp[0]=x.getKey();
tmp[1]=x.getValue();
pq.offer(tmp);
if(pq.size()>k){
pq.poll();
}
}
for(int i=0;i<k;i++){
res[i]=pq.poll()[0];
}
return res;
}
}
四、今日收获
学习+解题+记录=2h30min。