Stack & Queue

Stack:First In Last Out(FILO)

Queue:First In First Out(FIFO)

Stack ==> Queue:设置两个Stack(Input & Output),先存入Input,再倒入Output,最后从Output弹出

Queue ==> Stack

PriorityQueue:优先队列,优先级可设置
正常入、按照优先级出
实现机制:标准库
1、Heap堆(Binary,Binomial,Fibonacci),很多种实现形式
Mini Heap(小顶堆)
Max Heap(大顶堆)
2、Binary Search Tree


  1. Valid Parentheses
    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
    An input string is valid if:
    Open brackets must be closed by the same type of brackets.
    Open brackets must be closed in the correct order.
    Note that an empty string is also considered valid.
    思路:括号的合法性
    方法:堆栈 左括号--->push
    右括号-->peek-pop
    stack.isEmpty()
    code:
    class Solution {
    public boolean isValid(String s) {
    Stack stack = new Stack();
    for (char c : s.toCharArray()) {
    if (c == '(')
    stack.push(')');
    else if (c == '{')
    stack.push('}');
    else if (c == '[')
    stack.push(']');
    else if (stack.isEmpty() || stack.pop() != c)
    return false;
    }
    return stack.isEmpty();
    }
    }



703.Kth Largest Element in a Stream
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
思路:1、优先队列:O(logk)
2、排序:O(klogk)

code:

你可能感兴趣的:(Stack & Queue)