代码随想录算法训练营day62

503.下一个更大元素II

思路: 循环数组中得到元素下一个比它大的值,那么可以将两个本数组拼接,遍历即可。按照739. 每日温度的方法,在拼接数组中进行寻找。

复制代码
class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int> result(nums.size(),-1);
        if(nums.size()==0){
            return result;
        }
        stack<int> st;
        st.push(0);
        for(int i=1;i<nums.size()*2;i++){
            if(nums[i%nums.size()]<=nums[st.top()]){
                st.push(i%nums.size());
            }
            else{
                while(!st.empty()&&nums[i%nums.size()] > nums[st.top()]){
                    result[st.top()] = nums[i%nums.size()];
                    st.pop();
                }
                st.push(i%nums.size());
            }
        }
        return result;
    }
};

42. 接雨水

思路: 本体相当于求一个左右大于当前元素的位置,然后计算面积。要求左右比当前元素大,可以使用单调栈,使用递增栈,若当前元素大于栈顶,那么height[i]与栈顶的下一个元素就为他的左右元素,取最小h,计算宽度,即可得到现在的与水量。然后遍历所有元素。

复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> st;
        st.push(0);
        int result = 0;
        for (int i = 1; i < height.size(); i++) {
            if (height[i] < height[st.top()]) {
                st.push(i);
            } else if (height[i] == height[st.top()]) {
                st.pop();
                st.push(i);
            } else {
                while (!st.empty() && height[i] > height[st.top()]) {
                    int mid = height[st.top()];
                    st.pop();
                    if (!st.empty()) {
                        int h = min(height[i], height[st.top()]) - mid;
                        int w = i - st.top() - 1;
                        result += h * w;
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};
相关推荐
ToddyBear1 天前
从字符游戏到 CPU 指令集:一道算法题背后的深度思维跃迁
数据结构·算法
光影少年1 天前
前端算法新手如何刷算法?
前端·算法
yuniko-n1 天前
【力扣 SQL 50】子查询篇
数据库·sql·leetcode
Andyshengwx1 天前
图论 最小生成树 MST问题
c++·算法·图论
賬號封禁中miu1 天前
图论之最小生成树
java·数据结构·算法·图论
闻缺陷则喜何志丹1 天前
【图论 拓扑排序 贪心 临项交换】P5603 小 C 与桌游 题解|普及+
c++·算法·图论·贪心·拓扑排序·洛谷·临项交换
闻缺陷则喜何志丹1 天前
【图论 BFS染色 并集查找 】P3663 [USACO17FEB] Why Did the Cow Cross the Road III S|普及+
c++·算法·图论·染色法·宽度优先·并集查找
月明长歌1 天前
Java数据结构:PriorityQueue堆与优先级队列:从概念到手写大根堆
java·数据结构·python·leetcode·
青山如墨雨如画1 天前
【北邮-研-图论】网络最大流的标号算法V1.0
网络·算法·图论·北邮
chao1898441 天前
基于MATLAB实现NSGA-II算法
开发语言·算法·matlab