AcWing 803. 区间合并JAVA
原题链接
简单
作者:
理想二旬.
,
2021-05-04 15:03:37
,
所有人可见
,
阅读 238
JAVA 代码
import java.util.Scanner;
import java.util.Arrays;
public class Main{
static int n;
static int N = 200010; //2n
static int[][] segs, res;
static int segSize = 0; //统计segs区间的个数
static int resSize = 0; //统计合并后区间的个数
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
//存放题目数组
segs = new int[n][2];
res = new int[n][2];
//读
for(int i = 0; i < n; i ++){
segs[i][0] = sc.nextInt();
segs[i][1] = sc.nextInt();
segSize ++;
}
merge(segs);
System.out.println(resSize);
}
public static void merge(int[][] segs){
//排序
Arrays.sort(segs, (o1, o2) -> o1[0] - o2[0]);
//设置边界
int start = Integer.MAX_VALUE, end = Integer.MIN_VALUE;
int j = 0;
//循环区间个数次
for(int i = 0; i < segSize; i ++){
//取每个区间左右端点
int l = segs[i][0], r = segs[i][1];
//判断两个区间有无交集
if(end < l){
//不是第一次更新的话,就将其存储
if(start != Integer.MAX_VALUE){
res[j][0] = l;
res[j][1] = r;
j ++;
resSize ++;
}
//更新过来
start = l;
end = r;
}else{
//有交集,合并
end = Math.max(end, r);
}
}
if(start != Integer.MAX_VALUE){
res[j][0] = start;
res[j][1] = end;
resSize ++;
}
}
}