网站开发常用小图片,流行wordpress,结构优化,温州cms建站系统Problem: 739. 每日温度 文章目录 题目描述思路复杂度Code 题目描述 思路
若本题目使用暴力法则会超时#xff0c;故而使用单调栈解决#xff1a; 1.创建结果数组res#xff0c;和单调栈stack#xff1b; 2.循环遍历数组temperatures#xff1a; 2.1.若当stack不为空同时… Problem: 739. 每日温度 文章目录 题目描述思路复杂度Code 题目描述 思路
若本题目使用暴力法则会超时故而使用单调栈解决 1.创建结果数组res和单调栈stack 2.循环遍历数组temperatures 2.1.若当stack不为空同时栈顶所存储的索引对应的气温小于当前的气温则跟新res中对应位置的值 2.2.每次向stack中存入每日气温的索引下标 复杂度
时间复杂度: O ( n ) O(n) O(n)其中 n n n是数组temperatures的大小 空间复杂度: O ( n ) O(n) O(n) Code
class Solution {
public:/*** Monotone stack** param temperatures The given temperature array* return vectorint*/vectorint dailyTemperatures(vectorint temperatures) {int n temperatures.size();vectorint res(n);stackint stack;for (int i 0; i n; i) {while (!stack.empty() temperatures[stack.top()] temperatures[i]) {int index stack.top();stack.pop();res[index] i - index;}stack.push(i);}return res;}
};