每日温度(medium难度)
https://leetcode-cn.com/problems/daily-temperatures/
<方法一>:单调栈
class Solution {
public int[] dailyTemperatures(int[] T) {
int length = T.length;
int[] ans = new int[length];
Deque<Integer> stack = new LinkedList<Integer>();
for (int i = 0; i < length; i++) {
int temperature = T[i];
while (!stack.isEmpty() && temperature > T[stack.peek()]) {
int prevIndex = stack.pop();
ans[prevIndex] = i - prevIndex;
}
stack.push(i);
}
return ans;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/daily-temperatures/solution/mei-ri-wen-du-by-leetcode-solution/
来源:力扣(LeetCode)
<方法二>:
本方法思路及代码来源:
作者:pulsaryu
链接:https://leetcode-cn.com/problems/daily-temperatures/solution/jie-ti-si-lu-by-pulsaryu/
来源:力扣(LeetCode)
我们要找到快速的方法,在这道题中也就是要减少遍历的次数。
怎样减少遍历次数呢?我们可以分析,遍历一次数组中所有的值应该是少不了的,因为至少数组中每个值都需要计算一遍,所以时间复杂度肯定大于O(n)。关键是要减少为每个数寻找值遍历次数。
如下图所示,绿色部分区域会给多次遍历,如果我们能减少这部分区域的遍历次数,就能整体提高运算效率。
如果我们先从计算右边,那么我们计算过的位置就不需要重复计算,如图所示:
当前我们需要计算75位置,然后向右遍历到71,因为我们已经计算好了71位置对应的值为2,那么我们就可以直接跳2位再进行比较,利用了已经有的结果,减少了遍历的次数。
- 自上而下的递归思路:当前位置,询问下一个位置,你比我大,差值是1,你比我小,比你大的位置是谁,我去比较。这种思路很明显会出现重复子问题
- 自下而上的DP思路:最后一个位置,知道自己是0,接着倒数第二个,依次类推
public int[] dailyTemperatures(int[] T) {
int length = T.length;
int[] result = new int[length];
//从右向左遍历
for (int i = length - 2; i >= 0; i--) {
// j+= result[j]是利用已经有的结果进行跳跃
for (int j = i + 1; j < length; j+= result[j]) {
if (T[j] > T[i]) {
result[i] = j - i;
break;
} else if (result[j] == 0) { //遇到0表示后面不会有更大的值,那当然当前值就应该也为0
result[i] = 0;
break;
}
}
}
return result;
}
作者:pulsaryu
链接:https://leetcode-cn.com/problems/daily-temperatures/solution/jie-ti-si-lu-by-pulsaryu/
来源:力扣(LeetCode)