码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Intervals

时间:2014-09-30 11:53:39      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   ar   java   for   sp   div   art   

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].

答案

/**
 * 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)
    {
        if (intervals == null || intervals.size() <= 1)
        {
            return intervals;
        }
        Collections.sort(intervals, new Comparator<Interval>()
        {

            public int compare(Interval o1, Interval o2)
            {

                return o1.start - o2.start;
            }

        });
        int i = 0;
        while (i < intervals.size() - 1)
        {
            if (intervals.get(i).end >= intervals.get(i + 1).start)
            {
                intervals.get(i).start = Math.min(intervals.get(i).start,
                    intervals.get(i + 1).start);
                intervals.get(i).end = Math.max(intervals.get(i).end, intervals.get(i + 1).end);
                intervals.remove(i + 1);
                i-- ;
            }
            else
            {
                i++ ;
            }
            if (i < 0)
            {
                i++ ;
            }
        }
        return intervals;
    }
}


Merge Intervals

标签:style   color   io   ar   java   for   sp   div   art   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39693073

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