数据结构与算--堆实现线段树

题目

给定很多线段,每个线段都有两个数[start, end],表示线段开始位置和结束位置,左右都是闭区间,

规定:1. 线段开始和结束的位置一定都是整数值 2. 线段重合区域的长度必须>=1

返回线段最多重合区域中,包含了几条线段

java 复制代码
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Code_coverMax {

    public static void main(String[] args) {
        int[][] lines = {
                {1,100},{5,99},{2,105},{10,200}, {20,110},{30,202},{15,150}
        };

        int cover = maxCover1(lines);
        int[][] m = {
                {1,100},{5,99},{2,105},{10,200}, {20,110},{30,202},{15,150}
        };

        int cover2 = maxCover2(m);
        System.out.println(cover +" "+cover2);
    }

    public static int maxCover1(int[][] lines){
        int min = Integer.MAX_VALUE ;
        int max = Integer.MIN_VALUE;

        for (int i = 0; i < lines.length; i++) {
            min = Math.min(min,lines[i][0]);
            max = Math.max(min,lines[i][1]);
        }

        int cover = 0;
        for (double i = min+0.5; i < max; i = i+0.5) {
            int cur = 0;
            for (int j = 0; j < lines.length; j++) {
                if(lines[j][0] < i && lines[j][1] > i){
                    cur++;
                }
            }
            cover = Math.max(cover,cur);
        }

        return cover;
    }

    public static int maxCover2(int[][] m){
        Line[] lines = new Line[m.length];

        for (int i = 0; i < m.length; i++) {
            lines[i] = new Line(m[i][0],m[i][1]);
        }
        Arrays.sort(lines,new EndComparator());

        PriorityQueue<Integer> heap = new PriorityQueue<>(); // 小根堆
        int cover = 0;
        for (int i = 0; i < lines.length; i++) {
            int curStart = lines[i].start;
            while (!heap.isEmpty() && curStart>=heap.peek()){
                heap.poll();
            }

            heap.add(lines[i].end);
            cover = Math.max(cover,heap.size());
        }

        return cover;
    }

    public static class Line{
        public int start;
        public int end;
        public Line(int start, int end){
            this.start = start;
            this.end = end;
        }
    }

    public static class EndComparator implements Comparator<Line>{

        @Override
        public int compare(Line o1, Line o2) {
            return o1.start - o2.start;
        }
    }
}
相关推荐
2301_764441333 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI3 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
014-code3 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
Billlly4 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives4 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1234 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
java1234_小锋4 小时前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
fengfuyao9855 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
末央&5 小时前
【天机论坛】项目环境搭建和数据库设计
java·数据库
枫叶落雨2225 小时前
ShardingSphere 介绍
java