解题思路
将所维护的区间和下一段区间进行比较。
将st ed设置成-2e9的目的是为了让第一个区间可以方便进入
相关代码
import java.util.*;
public class Main {
public static void main(String[] args){
List<PII> list = new ArrayList();
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for(int i=0;i<n;i++) {
int l = scanner.nextInt();
int r = scanner.nextInt();
list.add(new PII(l,r));
}
//左端点进行排序
Collections.sort(list, new Comparator<PII>() {
@Override
public int compare(PII o1, PII o2) {
return o1.first-o2.first;
}
});
int count = 0; //记录有几个区间
int st = (int) -2e9;
int ed = (int)-2e9;
for(PII p:list){
if(p.first>ed){
count++;
st = p.first;
ed = p.second;
}
else{
ed = Math.max(ed,p.second);
}
}
System.out.println(count);
}
}
class PII {
int first;
int second;
PII(int first,int second){
this.first=first;
this.second=second;
}
}