package com.tang.project1.utils;
import java.util.Stack;
public class LeetCode739 {
static class Solution {
public static int[] dailyTemperatures(int[] temperatures){
//用栈存放运算中的数据的下标
//比如示例1中的73,在栈中存放的是0,74在栈中存放的是1
Stack<Integer> stack = new Stack<>();
//用来存放结果的数组
int[] res = new int[temperatures.length];
//遍历temperatures数组
for (int i = 0; i < temperatures.length; i++) {
//1.栈不为空,栈为空会报错
//2.栈中的栈顶元素小于即将入栈的元素
while (!stack.isEmpty()&& temperatures[i] > temperatures[stack.peek()]){
//此时把栈顶的元素下标获取
//73和74比较的时候,preIndex=0
//因为第一遍for循环的时候,没有进入while,直接把0存入栈中
int preIndex = stack.peek();
//第二遍for循环的时候,进入了while循环,此时i = 1
//所以此时为res[0] = 1
res[preIndex] = i - preIndex;
//将已经比较的元素弹出
stack.pop();
}
//把当天的温度的下标放入栈中
stack.push(i);
}
//返回已经比较好的元素数组
return res;
}
}
public static void main(String[] args) {
int[] temperatures = {73,74,75,71,69,72,76,73};
Solution.dailyTemperatures(temperatures);
}
}
每日温度( LeetCode 739 )---栈 (Java)
最新推荐文章于 2023-07-05 16:52:39 发布