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

寻找最合适的生育区域

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

全部评论

相关推荐

11-19 18:44
已编辑
成都理工大学 Java
程序员花海:我面试过100+校招生,大厂后端面试不看ACM,竞赛经历含金量低于你有几份大厂实习 这个简历整体来看不错 可以海投
如何写一份好简历
点赞 评论 收藏
分享
10-13 16:58
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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