239. 滑动窗口最大值
难点:
1,想好怎么快速找到区块内的最大数值,往常使用的是在遍历一次,但是是O(m*n)
思路:
1,使用单调队列,所有的数值都必须是从大到小,
2,用队列保持必要的顺序,而且对于大于K的循环,每次都要求pop push这两个操作
代码:
1 void pop(deque<int>& slidingWindow, int target) 2 { 3 if (!slidingWindow.empty() && slidingWindow.front() == target) 4 slidingWindow.pop_front(); 5 } 6 7 void push(deque<int>& slidingWindow, int target) 8 { 9 while (!slidingWindow.empty() && slidingWindow.back() < target) 10 { 11 slidingWindow.pop_back(); 12 } 13 14 slidingWindow.push_back(target); 15 } 16 17 vector<int> maxSlidingWindow(vector<int>& nums, int k) 18 { 19 vector<int> result; 20 deque<int> slidingWindow; 21 22 for (int i = 0; i < k; i++) 23 { 24 push(slidingWindow, nums[i]); 25 } 26 result.push_back(slidingWindow.front()); 27 28 for (int i = k; i < nums.size(); i++) 29 { 30 pop(slidingWindow, nums[i-k]); 31 32 push(slidingWindow, nums[i]); 33 34 result.push_back(slidingWindow.front()); 35 } 36 37 return result; 38 }