1019. The list of the next higher node

tips: I deeply understand their chicken dishes properties, monotonous stack concept using only raw, a little on how a change can not get out.

Due to the presence of repetitive elements in the list, the use of forward error on the order of monotonous pop will appear, can not simply use hashmap, after a round of wrestling chose to problem solution. . The original backwards to do so easily. .

A, pair <val, index> law, have the idea

 1 vector<int> nextLargerNodes(ListNode* head) {
 2     ListNode* temp = head;
 3     vector<int> res;
 4     pair<int, int> map;    //first:val        second:下标
 5     stack<pair<int,int>> use;
 6     int count = 0;
 7     while (temp != nullptr)
 8     {
 9         res.push_back(0);
10         while (!use.empty() && temp->val > use.top().first)
11         {
12             res[use.top().second] = temp->val;
13             use.pop();
14         }
15         use.push(make_pair(temp->val, count++));
16         temp = temp->next;
17     }
18     return res;
19 }

Second, backwards with monotonous stack, before flipping the list, I was hamburger

 1 vector<int> nextLargerNodes(ListNode* head) {
 2     ListNode* dummy = nullptr;
 3     ListNode* next = nullptr;
 4     ListNode* temp = head;
 5     while (temp != nullptr)
 6     {
 7         next = temp->next;
 8         temp->next = dummy;
 9         dummy = temp;
10         temp = next;
11     }
12     temp = dummy;
13 
14     stack<int> use;
15     stack<int> res;
16     while (temp != nullptr)
17     {
18         if (use.empty())
19         {
20             use.push(temp->val);
21             res.push(0);
22         }
23         else if (!use.empty() && temp->val < use.top())
24         {
25             res.push(use.top());
26             use.push(temp->val);
27         }
28         else
29         {
30             while (!use.empty() && temp->val >= use.top())
31             {
32                 use.pop();
33             }
34             if (use.empty())
35                 res.push(0);
36             else
37                 res.push(use.top());
38             use.push(temp->val);
39         }
40         temp = temp->next;
41     }
42     vector<int> result;
43     while (!res.empty())
44     {
45         result.push_back(res.top());
46         res.pop();
47     }
48     return result;
49 }

 

Guess you like

Origin www.cnblogs.com/zouma/p/11521480.html