803. 區間合併(貪心)

給定 nn 個區間 [li,ri][li,ri],要求合併全部有交集的區間。java

注意若是在端點處相交,也算有交集。node

輸出合併完成後的區間個數。ide

例如:[1,3]和[2,6]能夠合併爲一個區間[1,6]。this

輸入格式

第一行包含整數n。spa

接下來n行,每行包含兩個整數 l 和 r。code

輸出格式

共一行,包含一個整數,表示合併區間完成後的區間個數。xml

數據範圍

1n1000001≤n≤100000,
109liri109−109≤li≤ri≤109
blog

輸入樣例:

5
1 2
2 4
5 6
7 8
7 9

輸出樣例:


思路:先按區間左端點排序;下一個區間和上一個區間有三種狀況,在區間裏,有交集,無交集,以下圖
3

             

 

   代碼:排序

import java.util.*;
class node implements Comparable<node>{
    int l;
    int r;
      @Override
    public int compareTo(node o) {
           return this.l-o.l;
    }
}
public class Main{
        static final int max=100005;
        static node p[]=new node[max];
        public static void main(String[] args) {
               Scanner scan=new Scanner(System.in);
               int n=scan.nextInt();
               for(int i=0;i<n;i++){
                      p[i]=new node();
                      p[i].l=scan.nextInt();
                      p[i].r=scan.nextInt();
               }
               Arrays.sort(p,0,n);
               int res=1,end=p[0].r;
               for(int i=1;i<n;i++){
                    if(p[i].l<=end) end=Math.max(end, p[i].r);
                    else {
                        res++;
                        end=p[i].r;
                    }
               }
               System.out.println(res);
        }
}
相關文章
相關標籤/搜索