|
| 1 | +/* |
| 2 | +Given an array of integers temperatures represents the daily temperatures, |
| 3 | +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. |
| 4 | +If there is no future day for which this is possible, keep answer[i] == 0 instead. |
| 5 | + |
| 6 | +Example 1: |
| 7 | + |
| 8 | +Input: temperatures = [73,74,75,71,69,72,76,73] |
| 9 | +Output: [1,1,4,2,1,1,0,0] |
| 10 | +Example 2: |
| 11 | + |
| 12 | +Input: temperatures = [30,40,50,60] |
| 13 | +Output: [1,1,1,0] |
| 14 | +Example 3: |
| 15 | + |
| 16 | +Input: temperatures = [30,60,90] |
| 17 | +Output: [1,1,0] |
| 18 | + |
| 19 | +Constraints: |
| 20 | + |
| 21 | +1 <= temperatures.length <= 105 |
| 22 | +30 <= temperatures[i] <= 100 |
| 23 | +*/ |
| 24 | + |
| 25 | +/* |
| 26 | +Space Complexity : O(N) |
| 27 | +Time Complexity : O(NlogN) |
| 28 | +Difficulty level : Medium |
| 29 | +*/ |
| 30 | +class Solution { |
| 31 | +public: |
| 32 | + vector<int> dailyTemperatures(vector<int>& temperatures) { |
| 33 | + vector<int> ans(temperatures.size()); |
| 34 | + stack<int> s; |
| 35 | + |
| 36 | + for(int i=0; i<temperatures.size(); i++){ |
| 37 | + while(!s.empty() && temperatures[i] > temperatures[s.top()]){ |
| 38 | + const int k = s.top(); |
| 39 | + s.pop(); |
| 40 | + ans[k] = i - k; |
| 41 | + } |
| 42 | + s.push(i); |
| 43 | + } |
| 44 | + return ans; |
| 45 | + } |
| 46 | +}; |
0 commit comments