【LeetCode 热题 100】有效的括号 / 最小栈 / 字符串解码 / 柱状图中最大的矩形

⭐️个人主页:@小羊 ⭐️所属专栏:LeetCode 热题 100 很荣幸您能阅读我的文章,诚请评论指点,欢迎欢迎 ~

目录


有效的括号

cpp 复制代码
class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for (char e : s)
        {
            if (st.empty()) st.push(e);
            else if (st.top() == '(' && e == ')' || st.top() == '{' && e == '}'
                || st.top() == '[' && e == ']') st.pop();
            else st.push(e);
        }
        return st.empty();
    }
};

最小栈

cpp 复制代码
class MinStack {
    stack<int> st;
    stack<int> minst;
public:
    MinStack() {
        
    }
    
    void push(int val) {
        st.push(val);
        if (minst.empty() || val <= minst.top())
        {
            minst.push(val);
        }
    }
    
    void pop() {
        if (st.top() == minst.top())
        {
            minst.pop();
        }
        st.pop();
    }
    
    int top() {
        return st.top();
    }
    
    int getMin() {
        return minst.top();
    }
};

字符串解码

cpp 复制代码
class Solution {
public:
    string decodeString(string s) {
        int i = 0;
        return dfs(s, i);
    }
    string dfs(const string& s, int& i)
    {
        string str;
        while (i < s.size() && s[i] != ']')
        {
            if (isdigit(s[i]))
            {
                int num = 0;
                while (i < s.size() && s[i] != '[')
                {
                    num = num * 10 + s[i++] - '0';
                }
                i++; // 跳过'['
                string tmp = dfs(s, i);
                i++; // 跳过']'
                while (num--) str += tmp;
            }
            else str += s[i++];
        }
        return str;
    }
};

每日温度

cpp 复制代码
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        stack<int> st;
        vector<int> res(n);
        for (int i = 0; i < n; i++)
        {
            while (st.size() && temperatures[st.top()] < temperatures[i])
            {
                int t = st.top();
                st.pop();
                res[t] = i - t;
            }
            st.push(i);
        }
        return res;
    }
};

柱状图中最大的矩形

  1. 单调递增栈:分别从左向右和从右向左遍历,找到每个柱子左边和右边第一个比它矮的柱子位置。
  2. 计算宽度:对于每个柱子,其左右边界之间的距离即为矩形的宽度,高度为当前柱子的高度。
  3. 求最大值:遍历所有可能的矩形,找出面积最大的一个。
    单调栈。
cpp 复制代码
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size();
        vector<int> left(n), right(n);
        stack<int> st;
        for (int i = 0; i < n; i++)
        {
            while (st.size() && heights[st.top()] >= heights[i])
            {
                st.pop();
            }
            left[i] = st.empty() ? -1 : st.top();
            st.push(i);
        }
        st = stack<int>();
        for (int i = n - 1; i >= 0; i--)
        {
            while (st.size() && heights[st.top()] >= heights[i])
            {
                st.pop();
            }
            right[i] = st.empty() ? n : st.top();
            st.push(i);
        }
        int res = 0;
        for (int i = 0; i < n; i++)
        {
            res = max(res, (right[i] - left[i] - 1) * heights[i]);
        }
        return res;
    }
};

优化。

cpp 复制代码
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size();
        vector<int> left(n, -1), right(n, n);
        stack<int> st;
        for (int i = 0; i < n; i++)
        {
            while (st.size() && heights[st.top()] > heights[i])
            {
                right[st.top()] = i;
                st.pop();
            }
            if (st.size()) left[i] = st.top(); 
            st.push(i);
        }
        int res = 0;
        for (int i = 0; i < n; i++)
        {
            res = max(res, (right[i] - left[i] - 1) * heights[i]);
        }
        return res;
    }
};

数组中的第K个最大元素

建堆。

cpp 复制代码
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        for (int i = n - 2 / 2; i >= 0; i--)
        {
            adjust_down(nums, i, n);
        }
        while (--k)
        {
            swap(nums[0], nums[--n]);
            adjust_down(nums, 0, n);
        }
        return nums[0];
    }
    void adjust_down(vector<int>& nums, int parent, int n)
    {
        int child = 2 * parent + 1;
        while (child < n) 
        {
            if (child + 1 < n && nums[child + 1] > nums[child]) child++;
            if (nums[child] > nums[parent])
            {
                swap(nums[child], nums[parent]);
                parent = child;
                child = 2 * parent + 1;
            }
            else break;
        }
    }
};

快速选择。

cpp 复制代码
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        srand(time(nullptr));
        return qsort(nums, 0, nums.size() - 1, k);
    }
    int qsort(vector<int>& nums, int l, int r, int k)
    {
        if (l >= r) return nums[l];
        int key = nums[rand() % (r - l + 1) + l];
        int i = l, left = l - 1, right = r + 1;
        while (i < right) 
        {
            if (nums[i] < key) swap(nums[++left], nums[i++]);
            else if (nums[i] == key) i++;
            else swap(nums[--right], nums[i]);
        }
        int x = r - right + 1, y = right - left - 1;
        if (x >= k) return qsort(nums, right, r, k);
        else if (x + y >= k) return key;
        else return qsort(nums, l, left, k - x - y);
    }
};

前 K 个高频元素

建小堆,找出前K的最大的。

cpp 复制代码
class Solution {
    using pii = pair<int, int>;
    struct cmp{
        bool operator()(const pii& p1, const pii& p2)
        {
            return p1.second > p2.second;
        }
    };
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> hashmap;
        for (auto e : nums) hashmap[e]++;
        priority_queue<pii, vector<pii>, cmp> pq;
        for (auto& [a, b] : hashmap)
        {
            if (pq.size() == k)
            {
                if (b > pq.top().second)
                {
                    pq.pop();
                    pq.emplace(a, b);
                }
            } 
            else pq.emplace(a, b);
        }
        vector<int> res;
        while (pq.size())
        {
            res.push_back(pq.top().first);
            pq.pop();
        }
        return res;
    }
};

数据流的中位数

cpp 复制代码
class MedianFinder {
    priority_queue<int> left;
    priority_queue<int, vector<int>, greater<int>> right;
public:
    MedianFinder() {
        
    }
    
    void addNum(int num) {
        if (left.size() == right.size())
        {
            if (left.size() && num <= left.top()) left.push(num);
            else 
            {
                right.push(num);
                left.push(right.top());
                right.pop();
            }
        }
        else{
            if (num >= left.top()) right.push(num);
            else{
                left.push(num);
                right.push(left.top());
                left.pop();
            }
        }
    }
    
    double findMedian() {
        if (left.size() == right.size()) return (left.top() + right.top()) / 2.0;
        else return left.top();
    }
};

本篇文章的分享就到这里了,如果您觉得在本文有所收获,还请留下您的三连支持哦~

相关推荐
gfdhy1 天前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
Warren981 天前
Python自动化测试全栈面试
服务器·网络·数据库·mysql·ubuntu·面试·职场和发展
百***06011 天前
SpringMVC 请求参数接收
前端·javascript·算法
一个不知名程序员www1 天前
算法学习入门---vector(C++)
c++·算法
云飞云共享云桌面1 天前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑
福尔摩斯张1 天前
《C 语言指针从入门到精通:全面笔记 + 实战习题深度解析》(超详细)
linux·运维·服务器·c语言·开发语言·c++·算法
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!1 天前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi1 天前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
前端小L1 天前
图论专题(二十二):并查集的“逻辑审判”——判断「等式方程的可满足性」
算法·矩阵·深度优先·图论·宽度优先