classSolution{ publicintlongestSubarray(int[] nums, int limit){ int n = nums.length; int ans = 0; //枚举每一个子数组nums[i ... j] for(int i = 0; i < n; i++){ //初始化子数组中最大最小值 int min = nums[i], max = nums[i]; for(int j = i; j < n; j++){//对于每个子数组,更新最大最小值 if(nums[j] > max){ max = nums[j]; }elseif(nums[j] < min){ min = nums[j]; } //判断子数组是否满足条件并维护结果 if(max - min <= limit && j - i + 1 > ans){ ans = j - i + 1; } }
classSolution{ publicintlongestSubarray(int[] nums, int limit){ Deque<Integer> queMax = new LinkedList<Integer>(); Deque<Integer> queMin = new LinkedList<Integer>(); int n = nums.length; int left = 0, right = 0; int ret = 0; //枚举每一个右端点 right while (right < n) { while (!queMax.isEmpty() && queMax.peekLast() < nums[right]) { queMax.pollLast(); } while (!queMin.isEmpty() && queMin.peekLast() > nums[right]) { queMin.pollLast(); } queMax.offerLast(nums[right]); queMin.offerLast(nums[right]); //当 nums[left ... right]不满足条件时将 left 右移 while (!queMax.isEmpty() && !queMin.isEmpty() && queMax.peekFirst() - queMin.peekFirst() > limit) { if (nums[left] == queMin.peekFirst()) { queMin.pollFirst(); } if (nums[left] == queMax.peekFirst()) { queMax.pollFirst(); } left++; } ret = Math.max(ret, right - left + 1); right++; } return ret; } }
classSolution{ publicintlongestSubarray(int[] nums, int limit){ TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); int n = nums.length; int left = 0, right = 0; int ret = 0; while (right < n) { map.put(nums[right], map.getOrDefault(nums[right], 0) + 1); while (map.lastKey() - map.firstKey() > limit) { map.put(nums[left], map.get(nums[left]) - 1); if (map.get(nums[left]) == 0) { map.remove(nums[left]); } left++; } ret = Math.max(ret, right - left + 1); right++; } return ret; } }