day27

1.剑指 Offer 59 - I. 滑动窗口的最大值

 单调队列

 1 class Solution {
 2 public:
 3     vector<int> maxSlidingWindow(vector<int>& nums, int k) {
 4       vector<int> res;
 5       deque<int> q;
 6       int n = nums.size();
 7       for(int i = 0;i < n;i ++){
 8           while(!q.empty() && q.front() <= i - k)  q.pop_front();
 9           while(!q.empty() && nums[q.back()] < nums[i])  q.pop_back();
10           q.push_back(i);
11           if(q.back() >= k - 1)
12            res.push_back(nums[q.front()]);
13       }
14       return res;
15     }
16 };

 

2.剑指 Offer 59 - II. 队列的最大值

 
 1 class MaxQueue {
 2 public:
 3     queue<int> q;
 4     deque<int> deq;
 5     MaxQueue() {
 6 
 7     }
 8     
 9     int max_value() {
10       if(q.empty())  return -1;
11       return deq.front();
12     }
13     
14     void push_back(int value) {
15       q.push(value);
16       while(!deq.empty() && deq.back() <= value)
17        deq.pop_back();
18       deq.push_back(value);
19     }
20     
21     int pop_front() {
22       if(q.empty())  return -1;
23       int tmp = q.front();
24       q.pop();
25       if(tmp == deq.front())
26         deq.pop_front();
27       return tmp;
28     }
29 };
30 
31 /**
32  * Your MaxQueue object will be instantiated and called as such:
33  * MaxQueue* obj = new MaxQueue();
34  * int param_1 = obj->max_value();
35  * obj->push_back(value);
36  * int param_3 = obj->pop_front();
37  */

 

posted @ 2022-07-23 11:53  balabalahhh  阅读(14)  评论(0)    收藏  举报