代码随想录训练营第五十九天| 单调栈
今天是第五十九天,有经典的接雨水问题
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); Stack<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; } }
一样的模版题
class Solution { public int trap(int[] height) { int left = 0,right = height.length - 1; int maxLeft = 0,maxRight = 0; int ans = 0; while(left < right) { maxLeft = Math.max(maxLeft,height[left]); maxRight = Math.max(maxRight,height[right]); if(maxLeft < maxRight) { ans += maxLeft - height[left]; left++; }else { ans += maxRight - height[right]; right--; } } return ans; } }
不太会,之后再复习
今天的单调栈完成,明天是最后一天了,加油

浙公网安备 33010602011771号