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

寻找最合适的生育区域

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-05 15:27
点赞 评论 收藏
分享
牛客ID:561366855:期望薪资多少?难以相信这简历找不到工作。说明二本电子信息专业想对口就业非常难。
点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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