Leetcode 队和栈列 20 1047 150 239 347

20. Valid Parentheses

class Solution {
public:
    bool isValid(string s) {
        stack stk;
        if(s.size() % 2 == 1)
            return false;

        for(int i=0; i

有两种特殊情况,第一种,一出现就是右括号(代码中的体现是判断的时候要写stk.empty(), 不能只写不等)第二种是左括号多出来了(代码体现在最后return stk.empty)

1047. Remove All Adjacent Duplicates In String

class Solution {
public:
    string removeDuplicates(string s) {
        stack stk;

        for(int i=0; i

150. Evaluate Reverse Polish Notation

class Solution {
public:
    int evalRPN(vector& tokens) {
        stack stk;
        for(int i=0; i

239. Sliding Window Maximum 

class Solution {
private:
    class MyQueue{
    public:
        deque que;
        void pop(int val){
            if(!que.empty() && val == que.front()){
                que.pop_front();
            }
        }

        void push(int val){
            while(!que.empty() && val > que.back()){
                que.pop_back();
            }
            que.push_back(val);
        }

        int front(){
            return que.front();
        }
    };

public:
    vector maxSlidingWindow(vector& nums, int k) {
        MyQueue que;
        vector res;
        for(int i=0; i

347. Top K Frequent Elements

class Solution {
public:
    class mycomparison{
        public:
        bool operator()(const pair& lhs, const pair& rhs){
                return lhs.second > rhs.second;
        }
    };
    vector topKFrequent(vector& nums, int k) {
        unordered_map map;
        for(int i=0; i, vector>, mycomparison> pri_que;

        for(unordered_map :: iterator it = map.begin(); it != map.end(); it++){
            pri_que.push(*it);
            if(pri_que.size() > k){
                pri_que.pop();
            }
        }

        vector res(k);
        for(int i=k-1; i>=0; i--){
            res[i] = pri_que.top().first;
            pri_que.pop();
        }

        return res;
    }
};

这是小顶堆,小的先被弹出去(这道题只是看懂了)

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