题解 | #寻找最合适的生育区域#
寻找最合适的生育区域
https://www.nowcoder.com/practice/c183c254a5c94b9da341fb27fb3caf99
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param heights int整型一维数组 * @param k int整型 * @return int整型 */ public int findMaxRangeWithinThreshold (int[] heights, int k) { // write code here // 小根堆 PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> (a - b)); // 大根堆 PriorityQueue<Integer> pq2 = new PriorityQueue<>((a, b) -> (b - a)); int l = 0, res = Integer.MIN_VALUE; // 删除数据记录 HashMap<Integer, Integer> rec = new HashMap<>(); for (int r = 0; r < heights.length; r++) { pq.offer(heights[r]); pq2.offer(heights[r]); while (pq2.peek() - pq.peek() > k) { // 收缩左边界 int x = heights[l++]; rec.put(x, rec.getOrDefault(x, 0) + 1); while (!pq.isEmpty() && rec.containsKey(pq.peek())) { int temp = pq.poll(); rec.put(temp, rec.get(temp) - 1); if (rec.get(temp) == 0) rec.remove(temp); } while (!pq2.isEmpty() && rec.containsKey(pq2.peek())) { int temp = pq2.poll(); rec.put(temp, rec.get(temp) - 1); if (rec.get(temp) == 0) rec.remove(temp); } } res = Math.max(res, r - l + 1); } return res; } }