739. 每日温度
根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
算法思想链接:一看就懂的单调栈
链接: LeetCode 图解 | 739.每日温度.
java解法
stack.peek()和stack.pop()的异同:
//相同点:大家都返回栈顶的值。
//不同点:peek 不改变栈的值(不删除栈顶的值),pop会把栈顶的值删除。
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()]) { //如果栈不为空,并且当前温度大于栈顶元素温度
ans[stack.peek()] = i - stack.pop(); //就计算差值放入ans中,并让栈顶元素出栈
}
stack.push(i); //当栈为空,或者当前温度小于等于栈顶温度则入栈
}
return ans;
}
}
C语言解法
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
/*栈的复习*/
//定义栈结点
struct node {
int index;
};
//定义栈结构体
struct stack {
struct node *node;
int top;
int length;
};
//栈初始化
struct stack * init(int length)
{
struct stack *st = malloc(sizeof(struct stack) + length * sizeof(struct node));
st->node = (struct node *) (st + 1);
st->top = -1;
st->length = length;
return st;
}
//弹出栈顶元素并且返回栈顶值
int pop (struct stack *st)
{
int index = st->node[st->top].index;
st->top--;
return index;
}
void push(struct stack *st, int index)
{
st->top++;
st->node[st->top].index = index;
}
bool isEmpty(struct stack *st)
{
return st->top == -1;
}
int peek(struct stack *st)
{
return st->node[st->top].index;
}
int* dailyTemperatures(int* T, int TSize, int* returnSize){
*returnSize = TSize;
struct stack *st = init(TSize);
int *ans = malloc(TSize * sizeof(int));
for (int index = 0; index < TSize; index++) {
while(!isEmpty(st) && T[peek(st)] < T[index] ) { //如果栈不为空,并且当前温度大于栈顶元素温度
/*必须要把peek(st)单独拿出来赋值给idx,再去给ans数组寻找相应的值,否则就会出界错误()不知道为啥,呜呜呜呜呜*/
int idx = peek(st);
ans[idx] = index - pop(st); //就计算差值放入ans中,并让栈顶元素出栈
}
push(st,index); //当栈为空,或者当前温度小于等于栈顶温度则入栈
}
//此时还在栈里面的元素说明已经找不到比它大的温度了,即全部为0;
while(!isEmpty(st)) {
int index = pop(st);
ans[index] = 0;
}
return ans;
}