|
| 1 | +/* |
| 2 | + Given an array of temperatures, find the number of days after which the |
| 3 | + temperature becomes more than temperature of that day. |
| 4 | +
|
| 5 | + Ex. temperatures = [73,74,75,71,69,72,76,73] -> [1,1,4,2,1,1,0,0] |
| 6 | +
|
| 7 | + Time: O(N) |
| 8 | + Space: O(1) |
| 9 | +*/ |
| 10 | + |
| 11 | +/** |
| 12 | + * Note: The returned array must be malloced, assume caller calls free(). |
| 13 | + */ |
| 14 | +int*dailyTemperatures(int*temperatures,inttemperaturesSize,int*returnSize){ |
| 15 | +*returnSize=temperaturesSize; |
| 16 | + |
| 17 | +int*result= (int*)malloc(sizeof(int)*temperaturesSize); |
| 18 | + |
| 19 | +// Initialize result array to zero |
| 20 | +for (inti=0;i<temperaturesSize;++i)result[i]=0; |
| 21 | + |
| 22 | + |
| 23 | +for (inti=temperaturesSize-1;i >=0;--i) { |
| 24 | +intj=i+1; |
| 25 | + |
| 26 | +while (j<temperaturesSize&&temperatures[j] <=temperatures[i]) { |
| 27 | +if (result[j] <=0) |
| 28 | +break; |
| 29 | +j+=result[j]; |
| 30 | + } |
| 31 | + |
| 32 | +// If a day with higher temperature found, update result for that index |
| 33 | +if (j<temperaturesSize&&temperatures[j]>temperatures[i]) { |
| 34 | +result[i]=j-i; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | +returnresult; |
| 39 | +} |