原题链接:
https://leetcode.cn/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/
解法1: 滑动窗口 + 单调队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution {
public int longestSubarray(int[] nums, int limit) { TreeMap<Integer,Integer> mq = new TreeMap<>(((o1, o2) -> o1 - o2)); int left = 0 , right = 0; int ans = 0; int n = nums.length; while (right < n){ mq.put(nums[right], mq.getOrDefault(nums[right],0) + 1); while (mq.lastKey() - mq.firstKey() > limit){ mq.put(nums[left],mq.get(nums[left]) - 1); if(mq.get(nums[left]) == 0){ mq.remove(nums[left]); } left++; }
ans = Math.max(ans, right - left + 1); right++; }
return ans; } }
|