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

Merge Intervals

时间:2015-03-15 21:12:54      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

Merge Intervals

问题:

Given a collection of intervals, merge all overlapping intervals.

思路:

  不排序 直接上根据交集的特性

  排序后再判断

  简单的数学推导

我的代码1:

技术分享
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        if(intervals == null || intervals.size() == 0)  return intervals;
        for(int i = 0; i < intervals.size(); i++)
        {
            Interval interval = intervals.get(i);
            int min = interval.start;
            int max = interval.end;
            for(int j = i+1; j < intervals.size(); j++)
            {
                Interval tmp = intervals.get(j);
                if(isIntersect(interval, tmp))
                {
                    intervals.remove(j);
                    j--;
                    max = Math.max(max, tmp.end);
                    min = Math.min(min, tmp.start);
                }
            }
            if(min == interval.start && max == interval.end) i++;
            interval.start = min;
            interval.end = max;
            i--;
        }
        return intervals;
    }
    public boolean isIntersect(Interval one, Interval two)
    {
        int oneS = one.start;
        int oneE = one.end;
        int twoS = two.start;
        int twoE = two.end;
        if(oneE >= twoS && oneE <= twoE)    return true;
        if(twoE >= oneS && twoE <= oneE)    return true;
        if(oneE >= twoE && oneS <= twoS)    return true;
        if(twoE >= oneE && twoS <= oneS)    return true;
        return false;
    }
}
View Code

我的代码2:

技术分享
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        if(intervals == null || intervals.size() == 0)  return intervals;
        Collections.sort(intervals, new IntervalComparator());
        for(int i = 0; i < intervals.size() - 1; i++)
        {
            Interval one = intervals.get(i);
            Interval two = intervals.get(i+1);
            if(one.end >= two.start)
            {
                one.end = Math.max(one.end, two.end);
                intervals.remove(i+1);
                i--;
            }
        }
        return intervals;
    }
    private class IntervalComparator implements Comparator<Interval>
    {
        public int compare(Interval a, Interval b)
        {
            return a.start - b.start;
        }
    }
}
View Code

 

Merge Intervals

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4340345.html

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