代码随想录算法训练营第十一天

LeetCode.150 逆波兰表达式求值

题目链接 逆波兰表达式求值

题解

class Solution {
    public int evalRPN(String[] tokens) {
        Stack cstack = new Stack<>();
        Set set = new HashSet<>();
        set.add("+");
        set.add("-");
        set.add("*");
        set.add("/");
        int sum = 0;
        if(tokens.length == 1){
            return Integer.parseInt(tokens[0]);
        }
        for(int i = 0;i

解题思路

将"+","-","*","/"加入set集合,遍历字符串数组,如果该字符串在set集合内,代表其是运算符,将栈中两个整数弹出进行运算,再将运算结果压入栈中;如果该字符串不在set集合中说明该字符串是整数,将其转成整数压入栈中。

LeetCode.239 滑动窗口最大值

题目链接 滑动窗口最大值

题解

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
       if(nums.length == 1){
        return nums;
       }
       MyQueue deque = new MyQueue();
       int len = nums.length - k + 1;
       int n = 0;
       int[] res = new int[len];
       for(int i = 0;i deque = new LinkedList<>();
    void poll(int val){
        if(!deque.isEmpty() && val == deque.peek()){
            deque.poll();
        }
    }
    void add(int val){
        while(!deque.isEmpty() && val > deque.getLast()){
            deque.removeLast();
        }
        deque.add(val);
    }
    int peek(){
        return deque.peek();
    }
}

解题思路

自定义优先队列类,定义了弹出方法poll(),添加方法add(),获得队头方法(),具体题解看代码随想录讲解

你可能感兴趣的:(算法)