区间合并:区间合并问题

区间合并:区间合并问题

区间合并

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

  1. 按区间的左端点排序

  2. 扫描整个区间,在这过程中把可能有交点的区间合并

    1. 全包含:不做改动
    2. 相交:right 后移
    3. 相离:更新至下一个维护区间
Java 复制代码
import java.util.*;

public class Main {
    static final int N = 100010;
    static Pair[] pairs = new Pair[N];
    
    static class Pair implements Comparable<Pair> {
        int l, r;
        public Pair(int l, int r) {
            this.l = l;
            this.r = r;
        }
        
        @Override
        public int compareTo(Pair o) {
            if (this.l == o.l) {
                return this.r - o.r;
            }
            return this.l - o.l;
        }
    } 
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            int l = sc.nextInt();
            int r = sc.nextInt();
            pairs[i] = new Pair(l, r);
        }
        
        Arrays.sort(pairs, 0, n);
        int result = 1;
        int right = pairs[0].r;
        for (int i = 1; i < n; i++) {
            if (pairs[i].l <= right) {
                // 合并区间
                right = Math.max(right, pairs[i].r);
            } else {
                // 新区间
                result++;
                right = pairs[i].r;
            }
        }
        System.out.println(result);
    }
}
相关推荐
珍宝商店9 分钟前
原生 JavaScript 方法实战指南
开发语言·前端·javascript
喂完待续10 分钟前
【序列晋升】45 Spring Data Elasticsearch 实战:3 个核心方案破解索引管理与复杂查询痛点,告别低效开发
java·后端·spring·big data·spring data·序列晋升
郑重其事,鹏程万里13 分钟前
commons-exec
java
龙茶清欢14 分钟前
具有实际开发参考意义的 MyBatis-Plus BaseEntity 基类示例
java·spring boot·spring cloud·mybatis
神龙斗士24017 分钟前
Java 数组的定义与使用
java·开发语言·数据结构·算法
计算机学姐18 分钟前
基于微信小程序的扶贫助农系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
白露与泡影18 分钟前
2025互联网大厂高频Java面试真题解析
java·开发语言·面试
forever銳19 分钟前
java中如何保证接口幂等性
java·后端
柯南二号21 分钟前
【Java后端】MyBatis 和 MyBatis-Plus (MP) 的区别
java·数据库·tomcat
gopyer22 分钟前
180课时吃透Go语言游戏后端开发2:Go语言中的变量
开发语言·游戏·golang·游戏后端开发