/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_SIZE 100001
int* dailyTemperatures(int* temperatures, int temperaturesSize, int* returnSize){
*returnSize = temperaturesSize;
int *ans = (int*)calloc(temperaturesSize, sizeof(int));
int stack[MAX_SIZE] = {0};
int top = 0;
for (int i = 0; i < temperaturesSize; i++) {
/* 如果空栈或者下一个温度不比栈顶温度高,将下一个温度对应的下标入栈 */
if (top == 0 || temperatures[i] <= temperatures[stack[top]]) {
stack[++top] = i;
continue;
}
/* 下一个温度有可能比栈的前几个温度都大,因此需要循环比较,直到下一个温度比栈里的小 */
while (top != 0) {
if (temperatures[i] > temperatures[stack[top]]) {
ans[stack[top]] = i - stack[top];
stack[top--] = 0;
continue;
}
break;
}
/* 栈操作完成后,需要将这个新温度的下标入栈 */
stack[++top] = i;
}
return ans;
}