思路:
使用双端队列维护单调队列,因为过程中需要得到某一段数组的最大值和最小值,在单调队列的队首和队尾可以直接得到当前段的最值。
值得学习的好方法。
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
int ans = 0;
deque<int> q1, q2; //双端队列来维护单调队列
for (int i = 0, j = 0; i < nums.size(); i++){
while (!q1.empty() && q1.back() > nums[i]) q1.pop_back();//维护单调增队列
q1.push_back(nums[i]);
while (!q2.empty() && q2.back() < nums[i]) q2.pop_back();//维护单调减队列
q2.push_back(nums[i]);
//检测当前窗口是否满足条件
while (!q1.empty() && !q2.empty() && q2.front() - q1.front() > limit) {
if (nums[j] == q1.front()) q1.pop_front(); //从队头出队
if (nums[j] == q2.front()) q2.pop_front(); //从队头出队
j++;
}
ans = max(ans, i - j + 1);
}
return ans;
}
};