본문 바로가기

C

c++ leetcode 739 daily temperature code

code >>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using namespace std;
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        
        stack<pair<intint>> numSave;
        int n = temperatures.size();
        vector<int> indexes(n, 0);
        numSave.push({ temperatures[n - 1], n-1 });
        for (int i = n - 2; i>=0; i--)
        {
            if (temperatures[i] < temperatures[i+1])
            {
                indexes[i] = 1;
                numSave.push({ temperatures[i], i });
            }
            else
            {               
                while (!numSave.empty())
                {
                    int tmp_i = numSave.top().first;
                    int tmp_idx = numSave.top().second;                   
                    if (tmp_i > temperatures[i])
                    {
                        indexes[i] = tmp_idx - i;
                        numSave.push({ temperatures[i], i });
                        break;
                    }
                    else
                    {
                        numSave.pop();
                        if (numSave.empty())
                        {
                            indexes[i] = 0;
                            numSave.push({ temperatures[i], i });
                            break;
                        }
                    }
                }
 
            }            
        }
        return indexes;
    }
};