1、每日温度(lc739):
暴力解法(顺序暴力会超时)
public int [] dailyTemperatures1(int[] temperatures){
int n = temperatures.length;
int [] ans = new int[n];
Arrays.fill(ans,0);
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (temperatures[i] < temperatures[j]) {
ans[i] = j-i;
}
break;
}
}
return ans;
}
单调栈 解法:
public int[] dailyTemperatures(int[] temperatures){
//单调栈其实就是加入已经遍历过的元素
int len = temperatures.length;
int[] ans = new int[len];//初始元素就是0
Stack<Integer> stack = new Stack<>();
stack.push(0);//先将第一个元素推入
for (int i = 1; i < len; i++) {
if (temperatures[i] < temperatures[stack.peek()]) {
stack.push(i);
}//小于等于栈口元素则加入到栈中
if (temperatures[i] == temperatures[stack.peek()]) {
stack.push(i);
}else{
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
ans[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
}
return ans;
}
2、接雨水:
单调栈解法:
{
public int trap(int[] height) {
int len = height.length;
if (len < 3) return 0;
int ans = 0;
Stack<Integer> stack = new Stack<>();
stack.push(0);
for (int i = 1; i < len; i++) {
if (height[i] < height[stack.peek()]) {
stack.push(i);
}
if (height[i] == height[stack.peek()]){
stack.pop();
stack.push(i);
}else {
while (!stack.isEmpty() && height[i] > height[stack.peek()]){
int mid = stack.peek();
stack.pop();
if (!stack.isEmpty()) {
int h = Math.min(height[i],height[stack.peek()])-height[mid];
int w = i - stack.peek() - 1;
ans += h*w;
}
}
stack.push(i);
}
}
return ans;
}
}