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

寻找最合适的生育区域

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

全部评论

相关推荐

05-29 20:08
西南大学 golang
点赞 评论 收藏
分享
努力的小明a:项目看着很眼熟,施磊老师吧,我也学的这个😋我当时是把rpc框架做成了一个分布式网盘,这是一个项目,然后muduo库做成集群即时通讯,又用QT做了个交互的客户端,这样又一个项目,然后一个轻量redis,一个CAD,总共四个项目,投了三个月就今天2月份一个小厂Qt offer,然后后面想开了,Qt啥的都能干,这个月get了个北京大厂的offer,做java后端,人生就是这么魔幻,现在就在去北京入职的路上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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