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

题目

给定很多线段,每个线段都有两个数[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;
        }
    }
}
相关推荐
Orange--Lin3 分钟前
【用deepseek和chatgpt做算法竞赛】——还得DeepSeek来 -Minimum Cost Trees_5
人工智能·算法·chatgpt
mjr5 分钟前
设计模式-Java
java·设计模式
零星_AagT9 分钟前
Apache-CC6链审计笔记
java·笔记·apache·代码审计
01_10 分钟前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵
SylviaW0812 分钟前
python-leetcode 35.二叉树的中序遍历
算法·leetcode·职场和发展
篮l球场14 分钟前
LeetCodehot 力扣热题100
算法·leetcode·职场和发展
程序员张320 分钟前
使用IDEA提交SpringBoot项目到Gitee上
java·gitee·intellij-idea
pzx_00126 分钟前
【机器学习】K折交叉验证(K-Fold Cross-Validation)
人工智能·深度学习·算法·机器学习
BanLul27 分钟前
进程与线程 (三)——线程间通信
c语言·开发语言·算法
落羽的落羽33 分钟前
【落羽的落羽 数据结构篇】栈和队列
c语言·数据结构