码迷,mamicode.com
首页 > 编程语言 > 详细

Merge Intervals--Collections排序

时间:2018-07-02 00:03:17      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:col   .so   com   ret   max   exp   over   merge   TE   

First, sort the list, then merge from start to end.

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considerred overlapping.

/**
 * 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; }
 * }
 */
class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        List<Interval> l = new LinkedList<Interval>();
        if (intervals.size() == 0) return l;
        Collections.sort(intervals, new Comparator<Interval>() {
            @Override
            public int compare(Interval o1, Interval o2) {
                return o1.start - o2.start;
            }
        });
        Interval in = intervals.remove(0);
        l.add(in);
        for (Interval i : intervals) {
            if (in.end >= i.start) {
                in.end = Math.max(in.end,i.end);
            } else {
                l.add(i);
                in = i;
            }
        }
        return l;
    }
}

 

Merge Intervals--Collections排序

标签:col   .so   com   ret   max   exp   over   merge   TE   

原文地址:https://www.cnblogs.com/liudebo/p/9251675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!