LeetCode 刷题系列 -- 739. 每日温度
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入:temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90]
输出: [1,1,0]
提示:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
739. 每日温度 - 力扣(Leetcode)
思路 :单调栈结构解决三道算法题 :: labuladong的算法小抄
本题利用单调栈的方式。
单调栈模板:
// 存放答案的数组
int[] res =newint[n];
Stack<Integer> s =new Stack<>();
// 倒着往栈里放
for(int i = n -1; i >=0; i--){
// 判定个子高矮
while(!s.isEmpty()&& s.peek()<= nums[i])
{
// 矮个起开,反正也被挡着了。。。
s.pop();
}// nums[i] 身后的更大元素
res[i]= s.isEmpty()?-1: s.peek();
s.push(nums[i]);
}
c++:
class Solution {
public:vector<int> dailyTemperatures(vector<int>& temperatures) {int n = temperatures.size();vector<int> result(n, 0);stack<int> nums_stack;for(int i = n-1; i>=0; i--) {// 找到大于 i天温度的那天 jwhile(!nums_stack.empty() && temperatures[nums_stack.top()]<=temperatures[i]) {nums_stack.pop();}if(!nums_stack.empty()) {result[i] = nums_stack.top() - i; // j - i 表示下一个大于i天温度与 i 天距离的天数}nums_stack.push(i); // 压入 第 i 天}return result;}
};