首页 > 代码库 > leetcode 合并区间

leetcode 合并区间

使用最简单的排序方法;

 1 /** 2  * Definition for an interval. 3  * public class Interval { 4  *     int start; 5  *     int end; 6  *     Interval() { start = 0; end = 0; } 7  *     Interval(int s, int e) { start = s; end = e; } 8  * } 9  */10 public class Solution {11     public List<Interval> merge(List<Interval> intervals) {12         if(intervals.size()<=1) return intervals;13         ArrayList<Interval> arry=new ArrayList<Interval>();14         Comparator<Interval> cmp=new Comparator<Interval>(){15             public int compare(Interval v1,Interval v2)16             {17                 return v1.start-v2.start;18             }19                 20         21             22         };23             Collections.sort(intervals,cmp);24             Interval pre=intervals.get(0);25             for(int i=1;i<intervals.size();i++)26             {27                 Interval cur=intervals.get(i);28                 if(cur.start<=pre.end)29                 {30                   pre=new Interval(pre.start,Math.max(cur.end,pre.end));//merge31                   32                 }33                 else34                 {35                     arry.add(pre);36                     pre=cur;37                 }38                 39             }40             arry.add(pre);41             return arry;42            43     }44 }