栈与队列

232 用栈实现队列

class MyQueue {
    private Stack<Integer> stack1 = new Stack<>();
    private Stack<Integer> stack2 = new Stack<>();

    /** Initialize your data structure here. */
    public MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        peek();
        return stack2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if (!stack2.empty()) {
            return stack2.peek();
        } else {
            while (!stack1.empty()) {
                stack2.push(stack1.pop());
            }
            return stack2.peek();
        }
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        if (stack1.empty() && stack2.empty()) {
            return true;
        }
        return false;
    }
}

225 用队列来实现栈

//java中队列用LinkedList
//每次入栈操作就确保队列的前端元素为栈顶元素
class MyStack {
    private Queue<Integer> queue = new LinkedList<>();

    /** Initialize your data structure here. */
    public MyStack() {

    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        int n = queue.size();
        queue.add(x);
        for (int i = 0; i < n; i++){
            queue.add(queue.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}

20 有效的括号

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(')');
            } else if (s.charAt(i) == '[') {
                stack.push(']');
            } else if (s.charAt(i) == '{') {
                stack.push('}');
            } else if (stack.empty() || s.charAt(i) != stack.peek()) {
                return false;
            } else {
                stack.pop();
            }
        }
        return stack.empty();
    }
}

1047 删除字符串中的所有相邻重复项

class Solution {
    public String removeDuplicates(String S) {
        Stack<Character> stack = new Stack<>();
        String res = "";
        for (int i = 0; i < S.length(); i++) {
            if (stack.empty() || stack.peek() != S.charAt(i)) {
                stack.push(S.charAt(i));
            } else {
                stack.pop();
            }
        }
        while (!stack.empty()) {
            res = stack.pop() + res;
        }
        return res;
    }
}

150 逆波兰表达式求值

//leetcode中注意==和equals,idea中并不报错
class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            if (tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")) {
                int b = stack.pop();
                int a = stack.pop();
                if (tokens[i].equals("+")) {
                    stack.push(a + b);
                } else if (tokens[i].equals("-")) {
                    stack.push(a - b);
                } else if (tokens[i].equals("*")) {
                    stack.push(a * b);
                } else {
                    stack.push(a / b);
                }
            } else {
                stack.push(Integer.valueOf(tokens[i]));
            }
        }
        return stack.peek();
    }
}

239 滑动窗口最大值

class Solution {
    //定义单调队列
    class MyQueue {
        private Deque<Integer> deque = new LinkedList<>();

        void pop(int value) {
            if (!deque.isEmpty() && value == deque.peekFirst()) {
                deque.pollFirst();
            }
        }

        void push(int value) {
            while (!deque.isEmpty() && value > deque.peekLast()) {
                deque.pollLast();
            }
            deque.add(value);
        }

        int front() {
            return deque.peekFirst();
        }
    }
    public int[] maxSlidingWindow(int[] nums, int k) {
        MyQueue deque = new MyQueue();
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            deque.push(nums[i]);
        }
        arrayList.add(deque.front());
        for (int i = k; i < nums.length; i++) {
            deque.pop(nums[i - k]);
            deque.push(nums[i]);
            arrayList.add(deque.front());
        }
        int[] res = new int[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            res[i] = arrayList.get(i);
        }
        return res;
    }
}

347 前K个高频元素

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        //小顶堆,PriorityQueue默认是小顶堆
        PriorityQueue<Integer> queue = new PriorityQueue<>((var1, var2) -> map.get(var1) - map.get(var2));
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        Set<Integer> set = map.keySet();
        for (Integer i : set) {
            queue.add(i);
            if (queue.size() > k) {
                queue.poll();
            }
        }
        int[] res = new int[k];
        for (int i = queue.size() - 1; i >= 0; i--) {
            res[i] = queue.poll();
        }
        return res;
    }
}
posted @ 2021-01-16 21:13  叁柒零壹  阅读(46)  评论(0)    收藏  举报