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

Insert Interval

时间:2015-05-09 16:16:33      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

Insert Interval

问题:

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

思路:

  插入位置+merge

我的代码:

技术分享
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

他人代码:

技术分享
public class Solution {
    public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
        if (newInterval == null || intervals == null) {
            return intervals;
        }

        ArrayList<Interval> results = new ArrayList<Interval>();
        int insertPos = 0;

        for (Interval interval : intervals) {
            if (interval.end < newInterval.start) {
                results.add(interval);
                insertPos++;
            } else if (interval.start > newInterval.end) {
                results.add(interval);
            } else {
                newInterval.start = Math.min(interval.start, newInterval.start);
                newInterval.end = Math.max(interval.end, newInterval.end);
            }
        }

        results.add(insertPos, newInterval);

        return results;
    }
}
View Code

学习之处:

  • 我的代码需要进行两遍的扫描,别人代码需要一遍扫描,我的空间复杂度是O(1),别人的代码空间复杂度是O(n)

Insert Interval

标签:

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

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