代码随想录算法训练营 day 11|150. 逆波兰表达式求值 , 239. 滑动窗口最大值 , 347.前 K 个高频元素

一、 逆波兰表达式求值

题目及代码随想录解析

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值