# Leetcode 739. Daily Temperatures ###### tags: `Leetcode` 題目 Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. Example 1: Input: temperatures = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0] Example 2: Input: temperatures = [30,40,50,60] Output: [1,1,1,0] Example 3: Input: temperatures = [30,60,90] Output: [1,1,0] 解法: 1.把當下的溫度值拿來和存在stack的值比較,若有比較大,就把那個pop出來,然後當下的值就直接push進去,等待後面的審查 2.原本擔心會有先push進去的就不會被檢查到的問題,但根本不會發生,因為如果最上層的都出不去,那表示他下面的也一定都比他小,所以就檢查stack的最上層就好。喔對,難怪是要用stack,這題就是後進先出的概念= =。 3.malloc沒初始化、calloc可以初始化 ``` /** /** * Note: The returned array must be malloced, assume caller calls free(). */ int* dailyTemperatures(int* temperatures, int temperaturesSize, int* returnSize){ *returnSize = temperaturesSize; int* res = calloc(temperaturesSize, sizeof(int)); int stack[temperaturesSize]; int stackSize = 0;//index of stack = stackSize - 1 for(int i = 0; i < temperaturesSize; i++) { while(stackSize != 0 && temperatures[i] > temperatures[stack[stackSize-1]]) { res[stack[stackSize-1]] = i - stack[stackSize-1]; stackSize--; } stack[stackSize] = i; stackSize++; } return res; } ```