题目
题目地址:https://leetcode-cn.com/problems/daily-temperatures/
根据每日气温
列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用0
来代替。
例如,给定一个列表temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
,你的输出应该是[1, 1, 4, 2, 1, 1, 0, 0]
。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
答案
使用栈解决,遍历原数组,每一次循环都将该值与栈顶比较,如果较大,则进行出栈操作,并且每次将该值的下标压栈
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 36 37 38 39 40 41 42 43
| package com.jarome.leetcode;
import java.util.Stack;
public class SolutionDailyTemperatures {
public int[] dailyTemperatures(int[] T) { int[] res = new int[T.length]; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < T.length; i++) { if (i == 0) { stack.push(i); continue; } while (!stack.isEmpty()) { int peek = stack.peek(); if (T[i] > T[peek]) { int pop = stack.pop(); int day = i - pop; res[pop] = day; } else { break; } } stack.push(i); }
return res; }
public static void main(String[] args) { int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73}; SolutionDailyTemperatures st = new SolutionDailyTemperatures(); int[] ints = st.dailyTemperatures(temperatures); String res = ""; for (int i = 0; i < ints.length; i++) { res += ints[i]; } System.out.println(res); } }
|
执行情况: