下一个更大元素||
503. 下一个更大元素 II - 力扣(LeetCode)
和每日温度一样的套路,就是这里可以循环数组,两个数组拼接,然后循环两遍就行。
- public class Solution {
- public int[] NextGreaterElements(int[] nums) {
- int leng = nums.Length;
- int[] result = new int[leng];
- for(int i=0;i
-1; - if (leng == 0) return result;
- Stack<int> st = new Stack<int>();
- st.Push(0);
- for (int i = 1; i < leng * 2; i++) {
- if (nums[i % leng] < nums[st.Peek()]) st.Push(i % leng);
- else if (nums[i % leng] == nums[st.Peek()]) st.Push(i % leng);
- else {
- while (st.Count > 0 && nums[i % leng] > nums[st.Peek()]) {
- result[st.Peek()] = nums[i % leng];
- st.Pop();
- }
- st.Push(i % leng);
- }
- }
- return result;
- }
- }
接雨水
双指针法,例如i=4,然后从i开始向左右遍历直到找到左右的最高点,再找到左右的最小值减去i的高得到多少个容纳单位。
单调栈,也和每日温度一样三种情况,如果数组[i]的元素和栈头相同,得先弹出栈内元素再压入,因为最后求最高值是相同元素取最右边的元素,左边用不到;如果大于,取栈头做mid,然后取左右两遍的最小值做高,宽度是i-栈头(不是mid,mid已经弹出)-1,最后相乘就是容积。
- 双指针
- public class Solution {
- public int Trap(int[] height) {
- int sum = 0;
- for(int i=0;i
- if(i==0 || i==height.Length-1)continue;
- int lheight = height[i];
- int rheight = height[i];
- for(int l=i-1;l>=0;l--){
- if(lheight < height[l]) lheight=height[l];
- }
- for(int r=i+1;i
- if(rheight < height[i]) rheight=height[r];
- }
- int h = Math.Min(lheight,rheight) - height[i];
- if(h>0)sum+=h;
- }
- return sum;
- }
- }
-
- 单调栈
- public class Solution {
- public int Trap(int[] height) {
- Stack<int> stack = new Stack<int>();
- int sum = 0;
- stack.Push(0);
-
- for(int i=1;i
- if(height[i]
- stack.Push(i);
- }
- else if(height[i] == height[stack.Peek()]){
- stack.Pop();
- stack.Push(i);
- }else{
- while(stack.Count > 0 && height[i]>height[stack.Peek()]){
- int mid = stack.Pop();
- if(stack.Count > 0){
- int h = Math.Min(height[stack.Peek()],height[i])-height[mid];
- int w = i-stack.Peek()-1;
- sum+= h*w;
- }
- }
- stack.Push(i);
- }
- }
- return sum;
- }
- }
柱状图中最大的矩形
这题主要得注意数组前后都要加上0,如果没加上0,数组元素循环到栈内会一直跳过情况三,具体看代码随想录。
- public class Solution {
- public int LargestRectangleArea(int[] heights) {
- Stack<int> stack = new Stack<int>();
- int sum = 0;
- stack.Push(0);
-
- int[] newheights = new int[heights.Length+2];
- Array.Copy(heights,0,newheights,1,heights.Length);
- newheights[0] = 0;
- newheights[newheights.Length-1] = 0;
-
- for(int i=1;i
- if(newheights[i] > newheights[stack.Peek()]){
- stack.Push(i);
- }else if(newheights[i] == newheights[stack.Peek()]){
- stack.Pop();
- stack.Push(i);
- }else{
- while(stack.Count > 0 && newheights[i] < newheights[stack.Peek()]){
- int mid = stack.Pop();
- if(stack.Count > 0){
- int left = stack.Peek();
- int right = i;
- int w = right-left-1;
- int h = newheights[mid];
- sum = Math.Max(sum,h*w);
- }
- }
- stack.Push(i);
- }
- }
- return sum;
- }
- }
-
相关阅读:
Django 日志配置解析
正统类加载器Tomcat(tomcat二探)
洛谷题单 Part 2.3 二分答案
GB/T 40623-2021 船用防静电升高地板检测
JavaScript:基于任意JSON动态生成树状图(动态生成vue-giant-tree所需id、pid)
知识产权维权类型有哪些
免杀对抗-java语言-shellcode免杀-源码修改+打包exe
数学建模笔记-第十讲-聚类
低代码引擎 TinyEngine 正式发布!!!
工程机械——起重机导电滑环
-
原文地址:https://blog.csdn.net/evil_overall/article/details/134537595