单调栈
每日温度
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public int[] dailyTemperatures(int[] temperatures) { int len = temperatures.length; int[] res = new int[len]; Deque<Integer> stack = new LinkedList<>();
for(int i = 0; i < len; i++){ while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){ res[stack.peek()] = i - stack.peek(); stack.pop(); } stack.push(i); }
return res; } }
|
下一个更大元素 I
nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。
返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums1.length; i++){ map.put(nums1[i], i); }
int[] res = new int[nums1.length]; Stack<Integer> stack = new Stack<>(); Arrays.fill(res, -1);
for(int i = 0; i < nums2.length; i++){ while(!stack.isEmpty() && nums2[stack.peek()] < nums2[i]){ int prev = nums2[stack.pop()]; if(map.containsKey(prev)){ res[map.get(prev)] = nums2[i]; } } stack.push(i); }
return res; } }
|
接雨水
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public int trap(int[] height) { int len = height.length; if(len <= 2) return 0;
Stack<Integer> stack = new Stack<>(); stack.push(0);
int sum = 0; for(int i = 1; i < len; i++){ int top = stack.peek(); if(height[i] < height[top]){ stack.push(i); } else if(height[i] == height[top]){ stack.pop(); stack.push(i); } else { while(!stack.isEmpty() && height[i] > height[top]){ int mid = stack.pop(); if(!stack.isEmpty()){ int left = stack.peek(); int h = Math.min(height[left], height[i]) - height[mid]; int w = i - left - 1; sum += h * w; top = stack.peek(); } } stack.push(i); } }
return sum; } }
|
柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public int largestRectangleArea(int[] heights) { int[] newHeight = new int[heights.length + 2]; System.arraycopy(heights, 0, newHeight, 1, heights.length); newHeight[heights.length + 1] = 0; newHeight[0] = 0;
Stack<Integer> stack = new Stack<>(); stack.push(0);
int res = 0; for(int i = 1; i < newHeight.length; i++){ while(newHeight[i] < newHeight[stack.peek()]){ int mid = stack.pop(); int w = i - stack.peek() - 1; int h = newHeight[mid]; res = Math.max(res, h * w); } stack.push(i); }
return res; } }
|