代码随想录算法训练营Day61

编程入门 行业动态 更新时间:2024-10-14 10:39:34

代码随想录<a href=https://www.elefans.com/category/jswz/34/1770096.html style=算法训练营Day61"/>

代码随想录算法训练营Day61

代码随想录算法训练营Day61|单调栈02


文章目录

  • 代码随想录算法训练营Day61|单调栈02
  • 一、 503.下一个更大元素II
  • 二、42. 接雨水


一、 503.下一个更大元素II

class Solution {public int[] nextGreaterElements(int[] nums) {if(nums == null || nums.length <= 1) {return new int[]{-1};}int size = nums.length;int[] result = new int[size];//存放结果Arrays.fill(result,-1);//默认全部初始化为-1Stack<Integer> st= new Stack<>();for(int i = 0; i < 2*size; i++) {while(!st.empty() && nums[i % size] > nums[st.peek()]) {result[st.peek()] = nums[i % size];st.pop();}st.push(i % size);}return result;}
}

二、42. 接雨水

class Solution {public int trap(int[] height) {int length = height.length;if (length <= 2) return 0;int[] maxLeft = new int[length];int[] maxRight = new int[length];maxLeft[0] = height[0];for (int i = 1; i< length; i++) maxLeft[i] = Math.max(height[i], maxLeft[i-1]);maxRight[length - 1] = height[length - 1];for(int i = length - 2; i >= 0; i--) maxRight[i] = Math.max(height[i], maxRight[i+1]);int sum = 0;for (int i = 0; i < length; i++) {int count = Math.min(maxLeft[i], maxRight[i]) - height[i];if (count > 0) sum += count;}return sum;}
}

更多推荐

代码随想录算法训练营Day61

本文发布于:2023-12-04 17:17:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1661648.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   训练营   代码   随想录

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!