https://leetcode.com/contest/weekly-contest-61/problems/daily-temperatures/#.WiNrlKYs_6Y.sinaweibo
Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
这题O(n2)的代码小学生都能想到,我感觉它可以从后往前用某种递推关系O(1)来处理,但是想不出了。。暂时写下O(n2)的代码AC了晚上看看别的solution。
public int[] dailyTemperatures(int[] temperatures) {
if (temperatures == null || temperatures.length == 0) return temperatures;
int[] res = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
for (int j = i + 1; j < temperatures.length; j++) {
if (temperatures[i] < temperatures[j]) {
res[i] = j - i;
break;
}
}
}
return res;
}
看了下答案,没怎么仔细看,但是看出来是用空间换时间。从后往前,记录每个格子右边第一个比当前格子温度大的那个格子的index,这样比较次数会大大减少。