Why can I use a sliding window?
For a given interval [i,j] does not meet the requirements, then for the interval j'>j, [i,j'] does not meet the requirements, for i<i', [i',j], [i', j'] does not meet the requirements, i and j are monotonic.
Maintain a sliding window [i, j] to meet the requirements, in order to verify that [i, j] meets the requirements, we must maintain the maximum and minimum values of a period of time. The most direct idea, use map<int,int>
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
// 维护区间里的最大值以及最小值
map<int,int> treeMap;
int res = 0;
for(int i=0,j=0;j<nums.size();j++){
treeMap[nums[j]]++;
while(abs(nums[j]-treeMap.begin()->first)>limit||abs(nums[j]-treeMap.rbegin()->first)>limit){
treeMap[nums[i]]--;
if(treeMap[nums[i]]==0){
treeMap.erase(nums[i]);
}
i++;
}
res = max(res,j-i+1);
}
return res;
}
};
You can also use a monotonic queue to maintain the maximum and minimum values in the interval. This practice is left for consideration.