面试题59 - II. 队列的最大值

题目:

 

 

解答:

 1 class MaxQueue {
 2     queue<int> q;
 3     deque<int> d;
 4 public:
 5     MaxQueue() {
 6     }
 7     
 8     int max_value() 
 9     {
10         if (d.empty())
11             return -1;
12         return d.front();
13     }
14     
15     void push_back(int value) 
16     {
17         while (!d.empty() && d.back() < value) 
18         {
19             d.pop_back();
20         }
21         d.push_back(value);
22         q.push(value);
23     }
24     
25     int pop_front() 
26     {
27         if (q.empty())
28             return -1;
29         int ans = q.front();
30         if (ans == d.front()) 
31         {
32             d.pop_front();
33         }
34         q.pop();
35         return ans;
36     }
37 };

 

posted @ 2020-05-09 19:45  梦醒潇湘  阅读(139)  评论(0)    收藏  举报