力扣区间重叠问题

import java.util.Arrays;

/** * 区间重叠问题 * 1 4 * 1 2 * 2 3 * 3 4 */
public class Main4 {
    public static void main(String[] args) {
        int[][] cal= {{1,4},{1,2},{2,3},{3,4}};
        int n = cal.length;
        Cal[] times = new Cal[2*n];

        for (int i = 0; i < cal.length; i++) {
            int start = cal[i][0];
            int end = cal[i][1];
            Cal cStart = new Cal(start,true);
            Cal cEnd = new Cal(end,false);
            times[2*i] = cStart;
            times[2*i+1] = cEnd;
        }
        Arrays.sort(times);   // 使用自定义类中的排序方法
        // System.out.println(Arrays.toString(times));
        int active = 0;  // 表示当前正处于激活状态的日程
        int res = 0;
        for (int i = 0; i < times.length; i++) {
            Cal cur = times[i];
            if(cur.isActive){
                res = res + 1;
            }else{
                res = res - 1;
            }
            active = Math.max(active,res);
        }
        System.out.println(active);
    }
}


class Cal implements Comparable{
    int val;
    boolean isActive;  // true表明开始时间,false表明结束时间
    Cal(){}
    Cal(int val,boolean isActive){
        this.val = val;
        this.isActive = isActive;
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof Cal){
            Cal p = (Cal)o;
            if(this.val > p.val){
                return 1;
            }else if(this.val < p.val){
                return -1;
            }else{
                return 0;  // 当二者的val相等时,直接返回0,即按照前后顺序排序
            }
        }else{
            throw new RuntimeException("输入类型不匹配");
        }
    }

    @Override
    public String toString() {
        return "Cal{" +
                "val=" + val +
                ", isActive=" + isActive +
                '}';
    }
}