LeetCode刷题记录——队列、栈

  • Post author:
  • Post category:其他




20. 有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:


输入: "()"
输出: true

示例 2:


输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:


输入: "([)]"
输出: false

示例 5:


输入: "{[]}"
输出: true


分析:栈先入后出特点恰好与本题括号排序特点一致,即若遇到左括号入栈,遇到右括号时将对应栈顶左括号出栈,则遍历完所有括号后 stack 仍然为空


做法:如果 c 是左括号,则入栈 push,否则判断括号对应关系,若 stack 栈顶出栈括号 stack.pop() 与当前遍历括号 c 不对应,则提前返回 false。

class Solution {
public:
    bool isValid(string s) {
        int len = s.size();
        if (len == 0) 
            return true;
        if (len % 2 == 1)
            return false;
        char stack[len];
        int top = 0, mark;
        for (int i = 0; i < len; i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                mark = top;		// 记录上一次的top
                stack[top++] = s[i];
            }
            else if (top != 0 && s[i] == ')' && stack[mark] == '(') {
                mark--;
                top--;
            }
            else if (top != 0 && s[i] == ']' && stack[mark] == '[') {
                mark--;
                top--;
            }
            else if (top != 0 && s[i] == '}' && stack[mark] == '{') {
                mark--;
                top--;
            }
        }
        if (top == 0)
            return true;
        else 
            return false;
    }
};



232. 用栈实现队列

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false


说明:
    你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
    假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。


分析:由于队列是先进先出的,所以需要两个栈,将push的值放入pushs这个栈中,当需要pop时,如果pops这个栈为空,就将pushs栈中的全部值放入pops栈中,然后输出,这样就相当于队列的输出了


在这里插入图片描述

图片引用地址

class MyQueue {
private:
    stack<int> pushs,pops;

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

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        pushs.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (pops.empty())
            while (!pushs.empty()) {
                pops.push(pushs.top());
                pushs.pop();
            }

        int result = pops.top();
        pops.pop();
        return result;
    }
    
    /** Get the front element. */
    int peek() {
        if (pops.empty())
            while (!pushs.empty()) {
                pops.push(pushs.top());
                pushs.pop();
            }
        
        return pops.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
            return pushs.empty() && pops.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */



225. 用队列实现栈

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空

注意:

你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。


分析:这个题相对于用栈实现队列来说是比较简单的,我们只需要在push的时候,通过for循环将队列中元素的顺序倒置即可

class MyStack {
private:
    queue<int> q;

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

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for (int i = 0; i < q.size() - 1; i++) {
            q.push(q.front());
            q.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int result = q.front();
        q.pop();
        return result;

    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */



703. 数据流中的第K大元素

设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。

你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。

示例:

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3);   // returns 4
kthLargest.add(5);   // returns 5
kthLargest.add(10);  // returns 5
kthLargest.add(9);   // returns 8
kthLargest.add(4);   // returns 8

说明:
你可以假设 nums 的长度≥ k-1 且k ≥ 1。


分析:这题使用了优先队列,普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。



定义:priority_queue<Type, Container, Functional>




Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式。

//升序队列,小顶堆
priority_queue <int,vector<int>,greater<int> > queue;
//降序队列,大顶堆
priority_queue <int,vector<int>,less<int> >queue;


由于我们是按降序排列的,而且只在队列中存k个数,所以队列列头的元素就是第k大的元素了

class KthLargest {
private:
    int K;
    priority_queue<int, vector<int>, greater<int>> q;
public:
    KthLargest(int k, vector<int>& nums) {
        for (int n : nums) {
            q.push(n);
            if (q.size() > k)
                q.pop();
        }
        K = k;
    }
    
    int add(int val) {
        q.push(val);
        if (q.size() > K)
            q.pop();
        
        return q.top();
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */



版权声明:本文为qq_44039966原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。