栈、队列、优先队列、双端队列

视频教程:B站、网易云课堂、腾讯课堂
代码地址:Gitee、Github
存储地址:
百度云-提取码:
Google云

有效的括号:description
国内站

java版

/*
思路:
// 1. 暴力:不断replace匹配的括号 -> ""  时间复杂度:O(n^2)

// 2. 栈

*/


class Solution {
    private static final Map<Character,Character> map = new HashMap<Character,Character>(){{
        put('{','}'); put('[',']'); put('(',')'); put('?','?');
    }};
    public boolean isValid(String s) {
        if(s.length() > 0 && !map.containsKey(s.charAt(0))) return false;
        LinkedList<Character> stack = new LinkedList<Character>() {{ add('?'); }};
        for(Character c : s.toCharArray()){
            if(map.containsKey(c)) stack.addLast(c);
            else if(map.get(stack.removeLast()) != c) return false;
        }
        return stack.size() == 1;
    }
}

/*
评价:
优点:
缺点:
*/

python版:

'''
思路:

'''


class Solution:
    def isValid(self, s: str) -> bool:
        dic = {'{': '}',  '[': ']', '(': ')', '?': '?'}
        stack = ['?']
        for c in s:
            if c in dic: stack.append(c)
            elif dic[stack.pop()] != c: return False 
        return len(stack) == 1


'''
评价:
  优点:
  缺点:
'''

'''
思路:

'''
class Solution:
    def isValid(self, s: str) -> bool:
        dic = {')':'(',']':'[','}':'{'}
        stack = []
        for i in s:
            if stack and i in dic:
                if stack[-1] == dic[i]: stack.pop()
                else: return False
            else: stack.append(i)
            
        return not stack

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

国外站

java版

/*
思路:

*/




/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

最小栈:min-stack/

国内站

java版

/*
思路:

*/




/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

国外站

java版

/*
思路:

*/

class MinStack {
    int min = Integer.MAX_VALUE;
    Stack<Integer> stack = new Stack<Integer>();
    public void push(int x) {
        // only push the old minimum value when the current 
        // minimum value changes after pushing the new value x
        if(x <= min){          
            stack.push(min);
            min=x;
        }
        stack.push(x);
    }

    public void pop() {
        // if pop operation could result in the changing of the current minimum value, 
        // pop twice and change the current minimum value to the last minimum value.
        if(stack.pop() == min) min=stack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return min;
    }
}



/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

柱状图中最大的矩形:largest-rectangle-in-histogram/

国内站

java版

/*
思路:

*/




/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

国外站

java版

/*
思路:

*/

class Solution {
    public static int largestRectangleArea(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int[] lessFromLeft = new int[height.length]; // idx of the first bar the left that is lower than current
        int[] lessFromRight = new int[height.length]; // idx of the first bar the right that is lower than current
        lessFromRight[height.length - 1] = height.length;
        lessFromLeft[0] = -1;

        for (int i = 1; i < height.length; i++) {
            int p = i - 1;

            while (p >= 0 && height[p] >= height[i]) {
                p = lessFromLeft[p];
            }
            lessFromLeft[i] = p;
        }

        for (int i = height.length - 2; i >= 0; i--) {
            int p = i + 1;

            while (p < height.length && height[p] >= height[i]) {
                p = lessFromRight[p];
            }
            lessFromRight[i] = p;
        }

        int maxArea = 0;
        for (int i = 0; i < height.length; i++) {
            maxArea = Math.max(maxArea, height[i] * (lessFromRight[i] - lessFromLeft[i] - 1));
        }

        return maxArea;
    }
}

/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

滑动窗口最大值:sliding-window-maximum/

国内站

java版

/*
思路:

*/




/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

国外站

We scan the array from 0 to n-1, keep “promising” elements in the deque. The algorithm is amortized O(n) as each element is put and polled once.

At each i, we keep “promising” elements, which are potentially max number in window [i-(k-1),i] or any subsequent window. This means

If an element in the deque and it is out of i-(k-1), we discard them. We just need to poll from the head, as we are using a deque and elements are ordered as the sequence in the array

Now only those elements within [i-(k-1),i] are in the deque. We then discard elements smaller than a[i] from the tail. This is because if a[x] <a[i] and x<i, then a[x] has no chance to be the “max” in [i-(k-1),i], or any other subsequent window: a[i] would always be a better candidate.

As a result elements in the deque are ordered in both sequence in array and their value. At each step the head of the deque is the max element in [i-(k-1),i]
java版

/*
思路:

*/

class Solution {
    public int[] maxSlidingWindow(int[] a, int k) {		
            if (a == null || k <= 0) {
                return new int[0];
            }
            int n = a.length;
            int[] r = new int[n-k+1];
            int ri = 0;
            // store index
            Deque<Integer> q = new ArrayDeque<>();
            for (int i = 0; i < a.length; i++) {
                // remove numbers out of range k
                while (!q.isEmpty() && q.peek() < i - k + 1) {
                    q.poll();
                }
                // remove smaller numbers in k range as they are useless
                while (!q.isEmpty() && a[q.peekLast()] < a[i]) {
                    q.pollLast();
                }
                // q contains index... r contains content
                q.offer(i);
                if (i >= k - 1) {
                    r[ri++] = a[q.peek()];
                }
            }
            return r;
        }
}


/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

设计循环双端队列:design-circular-deque/

国内站

java版

/*
思路:

*/




/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

国外站

java版

/*
思路:

*/

class MyCircularDeque {
    int size;
    int k;
    DoubleListNode head;
    DoubleListNode tail;
    /** Initialize your data structure here. Set the size of the deque to be k. */
    public MyCircularDeque(int k) {
        head = new DoubleListNode(-1);
        tail = new DoubleListNode(-1);
        head.pre = tail;
        tail.next = head;
        this.k = k;
        this.size = 0;
    }
    
    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    public boolean insertFront(int value) {
        if (size == k)
            return false;
        DoubleListNode node = new DoubleListNode(value);
        node.next = head;
        node.pre = head.pre;
        head.pre.next = node;
        head.pre = node;
        size++;
        return true;
    }
    
    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    public boolean insertLast(int value) {
        if (size == k)
            return false;
        DoubleListNode node = new DoubleListNode(value);
        node.next = tail.next;
        tail.next.pre = node;
        tail.next = node;
        node.pre = tail;
        size++;
        return true;
    }
    
    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    public boolean deleteFront() {
        if (size == 0)
            return false;
        head.pre.pre.next = head;
        head.pre = head.pre.pre;
        size--;
        return true;
    }
    
    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    public boolean deleteLast() {
        if (size == 0)
            return false;
        tail.next.next.pre = tail;
        tail.next = tail.next.next;
        size--;
        return true;
    }
    
    /** Get the front item from the deque. */
    public int getFront() {
        return head.pre.val;
    }
    
    /** Get the last item from the deque. */
    public int getRear() {
        return tail.next.val;
    }
    
    /** Checks whether the circular deque is empty or not. */
    public boolean isEmpty() {
        return size == 0;
    }
    
    /** Checks whether the circular deque is full or not. */
    public boolean isFull() {
        return size == k;
    }
}

class DoubleListNode {
    DoubleListNode pre;
    DoubleListNode next;
    int val;
    public DoubleListNode(int val) {
        this.val = val;
    }
}


/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

接雨水:trapping-rain-water/

国内站

java版

/*
思路:

*/




/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

国外站

java版

/*
思路:

*/

class Solution {
    public int trap(int[] A){
        int a=0;
        int b=A.length-1;
        int max=0;
        int leftmax=0;
        int rightmax=0;
        while(a<=b){
            leftmax=Math.max(leftmax,A[a]);
            rightmax=Math.max(rightmax,A[b]);
            if(leftmax<rightmax){
                max+=(leftmax-A[a]);       // leftmax is smaller than rightmax, so the (leftmax-A[a]) water can be stored
                a++;
            }
            else{
                max+=(rightmax-A[b]);
                b--;
            }
        }
        return max;
    }
}


/*
评价:
优点:
缺点:
*/

python版:



'''
思路:

'''

'''
评价:
  优点:
  缺点:
'''

c++版:

/*
思路:

*/


/*
评价:
优点:
缺点:
*/

一 栈和队列的实现与特性

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

二 实战题目解析:有效的括号、最小栈等问题

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值