Day37 | 739. 每日温度、496. 下一个更大元素 I、503. 下一个更大元素 II、42. 接雨水、84. 柱状图中最大的矩形
739. 每日温度
题目链接:739. 每日温度 - 力扣(LeetCode)
题目难度:中等
代码:
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int lens=temperatures.length;
int[] res=new int[lens];
Deque<Integer> stack=new LinkedList<>();
for(int i=0;i<lens;i++){
while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
res[stack.peek()]=i-stack.peek();
stack.pop();
}
stack.push(i);
}
return res;
}
}
496. 下一个更大元素 I
题目链接:496. 下一个更大元素 I - 力扣(LeetCode)
题目难度:简单
代码:
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 pre=nums2[stack.pop()];
if(map.containsKey(pre))
res[map.get(pre)]=nums2[i];
}
stack.push(i);
}
return res;
}
}
503. 下一个更大元素 II
题目链接:503. 下一个更大元素 II - 力扣(LeetCode)
题目难度:中等
代码:
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res=new int[nums.length];
Arrays.fill(res,-1);
Stack<Integer> stack=new Stack<>();
for(int i=0;i<nums.length*2;i++){
while(!stack.isEmpty()&&nums[i%nums.length]>nums[stack.peek()]){
res[stack.peek()]=nums[i%nums.length];
stack.pop();
}
stack.push(i%nums.length);
}
return res;
}
}
42. 接雨水
题目链接:42. 接雨水 - 力扣(LeetCode)
题目难度:困难
代码:
class Solution {
public int trap(int[] height) {
int size=height.length;
if(size<=2) return 0;
Stack<Integer> stack=new Stack<>();
stack.push(0);
int sum=0;
for(int i=0;i<size;i++){
int stackTop=stack.peek();
if(height[i]<height[stackTop])
stack.push(i);
else if(height[i]==height[stackTop]){
stack.pop();
stack.push(i);
}else{
int heightAtIdx=height[i];
while(!stack.isEmpty()&&(heightAtIdx>height[stackTop])){
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;
stackTop=stack.peek();
}
}
stack.push(i);
}
}
return sum;
}
}
84. 柱状图中最大的矩形
题目链接:84. 柱状图中最大的矩形 - 力扣(LeetCode)
题目难度:困难
代码:
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> st = new Stack<Integer>();
int [] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int index = 0; index < heights.length; index++){
newHeights[index + 1] = heights[index];
}
heights = newHeights;
st.push(0);
int result = 0;
for (int i = 1; i < heights.length; i++) {
if (heights[i] > heights[st.peek()]) {
st.push(i);
} else if (heights[i] == heights[st.peek()]) {
st.pop();
st.push(i);
} else {
while (heights[i] < heights[st.peek()]) {
int mid = st.peek();
st.pop();
int left = st.peek();
int right = i;
int w = right - left - 1;
int h = heights[mid];
result = Math.max(result, w * h);
}
st.push(i);
}
}
return result;
}
}