56. Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

For example,

Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

一刷
题解:
使用Comparator来对集合进行sort。 Comparator和Comparable是两个很重要的interface,再加上interable,runnable等,要好好掌握。

Time Complexity O(n), space complexity O(1)

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> res = new ArrayList<>();
        if(intervals == null || intervals.size() == 0)
            return res;
        Collections.sort(intervals, new InterComparator());
        
        Interval last = intervals.get(0);
        for(int i=1; i<intervals.size(); i++){
             Interval curr = intervals.get(i);
             if(last.end < curr.start){
                 res.add(last);
                 last = curr;
             }
             else{
                 if(curr.end>last.end){
                     last.end = curr.end;
                 }
             }
        }
        
        res.add(last);
        return res;
    }
    
    public class InterComparator implements Comparator<Interval>{
        public int compare(Interval a, Interval b){
            return a.start - b.start;
        }
    }
}

也可以不用构造新类

  Collections.sort(intervals, new Comparator(){
  public int compare(Interval a, Interval b){
  return a.start - b.start;
}
});

二刷
题解:
先把list按照起始时间ascending排序,然后通过比较end判断是否要merge

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> res = new ArrayList<>();
        if(intervals == null || intervals.size()<=1) return intervals;
        Collections.sort(intervals, new Comparator<Interval>(){
          public int compare(Interval a, Interval b){
              return a.start - b.start;
            }  
            });
        Interval cur = intervals.get(0);
        for(int i=1; i<intervals.size(); i++){
            if(intervals.get(i).start<=cur.end && intervals.get(i).end > cur.end){
                cur.end = intervals.get(i).end;
            }
            else if(intervals.get(i).start>cur.end){
                res.add(cur);
                cur = intervals.get(i);
            }
        }
        res.add(cur);
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容