题解 | #寻找最合适的生育区域#

寻找最合适的生育区域

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;
    }
}

全部评论

相关推荐

2025-11-13 20:16
已编辑
厦门理工学院 软件测试
专业嗎喽:硕佬,把学校背景放后面几段,学校背景双非还学院,让人看了就不想往下看。 把实习经历和个人奖项放前面,用数字化简述自己实习的成果和掌握的技能,比如负责项目一次通过率90%,曾4次发现项目潜在问题风险为公司减少损失等等
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务