区间合并讲解

简介: 区间合并讲解

y总模板:


// 将所有存在交集的区间合并
void merge(vector<PII> &segs)
{
vector<PII> res;
sort(segs.begin(), segs.end());
int st = -2e9, ed = -2e9;
for (auto seg : segs)
if (ed < seg.first)
{
if (st != -2e9) res.push_back({st, ed});
st = seg.first, ed = seg.second;
}
else ed = max(ed, seg.second);
if (st != -2e9) res.push_back({st, ed});
segs = res;
}


https://www.acwing.com/problem/content/805/

思路:

1.将每个区间左端点排序

2.如果下一个区间左端点大于老区间右端点,则找到了新区间,数量+1,添加新区间

否则更新较大的右端点


public static void main(String[] args) throws IOException {
        Scanner sc=new Scanner(System.in);
        int n= sc.nextInt();
        ArrayList<int []> list=new ArrayList<>();
        while (n-->0){
            int []a=new int [2];
            a[0]=sc.nextInt();
            a[1]=sc.nextInt();
            list.add(a);
        }
        System.out.println(merge(list));
    }
    public static int merge(ArrayList <int []> list){
        ArrayList <int []> newlist=new ArrayList<>();
        //对每个区间的左区间点进行升序排列
        list.sort(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]-o2[0];
            }
        });
        int l=Integer.MIN_VALUE,r=Integer.MIN_VALUE;
        for (int[] a : list) {
            //如果新的左区间大于旧的右区间
            if(a[0]>r){
                //那么意味着这是一个新区间,与原来区间不一样
                if(l!=Integer.MIN_VALUE) {
                    newlist.add(new int[]{l, r});
                }
                l=a[0];
                r=a[1];
            }else{
                r=Math.max(r,a[1]);
            }
        }
        if(l!=Integer.MIN_VALUE)  newlist.add(new int[]{l,r});
        list.clear();
        for (int[] b : newlist) {
            list.add(b);
        }
        return list.size();
    }
相关文章
|
存储 人工智能 自然语言处理
云上玩转DeepSeek系列之二:PAI+DeepSeek,打造智能问答助手
本文将为您带来“PAI+DeepSeek,30分钟打造支持连网搜索+私有知识库的智能应用”最佳实践,大模型能力、联网能力再加持 RAG 方案,实现 DeepSeek 系列模型与现有业务的高效融合。
|
SQL 监控 关系型数据库
关系型数据库数据恢复步骤
【7月更文挑战第1天】
485 2
|
SQL 关系型数据库 MySQL
mysql Lock wait timeout exceeded; try restarting transaction解决方案
在测试程序时,打的断点怎么都跳不进去,console一直报 “Lock wait timeout exceeded; try restarting transaction”
470 0
|
存储 JavaScript 前端开发
js中 for、forEach、for...in、for...of循环的区别和使用
js中 for、forEach、for...in、for...of循环的区别和使用
224 0
|
前端开发
前端项目实战玖拾陆react-admin+material ui-踩坑-List的用法之Empty来设置空列表
前端项目实战玖拾陆react-admin+material ui-踩坑-List的用法之Empty来设置空列表
271 0
|
运维 Cloud Native 前端开发
带你读《企业级云原生白皮书项目实战》——7.3 低代码、无代码
带你读《企业级云原生白皮书项目实战》——7.3 低代码、无代码
199 0
|
前端开发 Java
springboot统一处理返回实体与异常抛出
springboot统一处理返回实体与异常抛出
524 0
springboot统一处理返回实体与异常抛出
|
安全 网络安全 数据安全/隐私保护
|
14天前
|
人工智能 数据可视化 安全
王炸组合!阿里云 OpenClaw X 飞书 CLI,开启 Agent 基建狂潮!(附带免费使用6个月服务器)
本文详解如何用阿里云Lighthouse一键部署OpenClaw,结合飞书CLI等工具,让AI真正“动手”——自动群发、生成科研日报、整理知识库。核心理念:未来软件应为AI而生,CLI即AI的“手脚”,实现高效、安全、可控的智能自动化。
34769 39
王炸组合!阿里云 OpenClaw X 飞书 CLI,开启 Agent 基建狂潮!(附带免费使用6个月服务器)