编程语言
首页 > 编程语言> > java_day21

java_day21

作者:互联网

目标:Java web开发

问题:还是写知识点吧,写题目没人看:重写接口,增强for循环

import java.util.*;
class Interval implements Comparable<Interval>{
    public int l,r;
    public Interval(int l,int r){
        this.l=l;
        this.r=r;
    }
    public int compareTo(Interval p){//返回值-1,0或1
        return Integer.compare(l,p.l);
    }
}
public class Main{
    public static void main(String[] args){
        List<Interval> intervals=new ArrayList<>();
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        while(n-->0){
            int l=sc.nextInt();
            int r=sc.nextInt();
            intervals.add(new Interval(l,r));
        }
        Collections.sort(intervals);//对List进行排序
        int l=intervals.get(0).l;
        int r=intervals.get(0).l;
        int cnt=0;
        for(Interval p:intervals){//增强for循环
            if(p.l<=r) r=Math.max(r,p.r);
            else{
                l=p.l;
                r=p.r;
                cnt++;
            }
        }
        System.out.println(cnt+1);
    }
}

标签:java,int,Interval,day21,nextInt,intervals,sc,public
来源: https://www.cnblogs.com/zhuangzhongxu/p/15077303.html