算法-每日温度

1. 温度升高天数

根据每日 气温列表,重新生成一个列表,对应位置的数字是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,在该位置用 0 来代替

  • 例如给定列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
    输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

2. 解法

遍历目标数组,使用栈结构来存储数组中元素的下标值。遍历的同时进行比较判断,将数组当前遍历的元素与栈顶下标对应的数组元素比较:

  • 如果栈顶存储的下标对应的数组元素较小,则将该下标出栈,并计算其与数组当前遍历的元素下标的差值,存入辅助数组的栈顶下标位置
  • 如果不符合以上条件,则将当前下标存入栈中
public int[] dailyTemperatures(int[] temperatures) {
    int n = temperatures.length;
    int[] dist = new int[n];
    Stack<Integer> indexs = new Stack<>();
    for (int current = 0; current < n; current++) {
        while (!indexs.isEmpty() && temperatures[current] > temperatures[indexs.peek()]) {
            int preIndex = indexs.pop();
            dist[preIndex] = current - preIndex;
        }
        indexs.add(curIndex);
    }
    return dist;
}
发布了97 篇原创文章 · 获赞 88 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_45505313/article/details/103652787
今日推荐