【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();
    }
};

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

相关推荐
刃神太酷啦17 分钟前
聚焦 string:C++ 文本处理的核心利器--《Hello C++ Wrold!》(10)--(C/C++)
java·c语言·c++·qt·算法·leetcode·github
CoovallyAIHub18 分钟前
云南电网实战:YOLOv8m改进模型攻克输电线路异物检测难题技术详解
深度学习·算法·计算机视觉
蜗牛的旷野24 分钟前
华为OD机试_2025 B卷_磁盘容量排序(Python,100分)(附详细解题思路)
python·算法·华为od
Sun_light33 分钟前
链表 --- 高效离散存储的线性数据结构
前端·javascript·算法
西西弗Sisyphus34 分钟前
低秩分解的本质是通过基矩阵和系数矩阵的线性组合,以最小的存储和计算代价近似表示复杂矩阵
线性代数·算法·矩阵
物联网嵌入式小冉学长1 小时前
10.C S编程错误分析
c语言·stm32·单片机·算法·嵌入式
王中阳Go18 小时前
从超市收银到航空调度:贪心算法如何破解生活中的最优决策谜题?
java·后端·算法
故事挺秃然19 小时前
中文分词:机械分词算法详解与实践总结
算法·nlp
车队老哥记录生活21 小时前
【MPC】模型预测控制笔记 (3):无约束输出反馈MPC
笔记·算法
地平线开发者1 天前
BEV 感知算法评价指标简介
算法·自动驾驶